📌 Understanding the this Keyword in Java (with a simple example) In Java, the this keyword is a reference to the current object of a class. It’s commonly used to differentiate instance variables from method or constructor parameters when they share the same name. Let’s look at a simple example 👇 class Employee { String name; int age; // Constructor Employee(String name, int age) { this.name = name; this.age = age; } void display() { System.out.println("Name: " + this.name); System.out.println("Age: " + this.age); } public static void main(String[] args) { Employee emp = new Employee("Vishnu", 28); emp.display(); } } 🔍 What’s happening here? this.name refers to the instance variable of the current object. name (without this) refers to the constructor parameter. Without this, Java would get confused between the two variables. Using this makes the code clear, readable, and bug-free. ✅ Why this is important? Avoids variable shadowing Improves code clarity Helps in constructor chaining and method calls Essential for writing clean object-oriented code Mastering small concepts like this builds a strong Java foundation 💪 #Java #OOP #Programming #Backend #Learning #CleanCode
Java this Keyword Explained with Example
More Relevant Posts
-
🚀 Learning Core Java – Mutable Strings in Java Today I explored Mutable Strings in Java and how they differ from immutable String objects. Unlike the String class (which is immutable), mutable strings allow us to modify the same object without creating new objects in memory. Java provides two classes for mutable strings: 🔹 StringBuffer 🔹 StringBuilder ⸻ 🔹 Default Capacity Both StringBuffer and StringBuilder have a default capacity of 16 characters. When the content exceeds the current capacity, Java automatically increases the size using this formula: 👉 New Capacity = (Current Capacity × 2) + 2 This allows dynamic resizing without manual memory handling. ⸻ 🔹 Important Methods ✔ append() Adds new content to the end of the existing string without creating a new object. ✔ delete() Allows modification by removing specific characters from the existing string. ✔ trimToSize() Reduces the capacity to match the current content length, optimizing memory usage. ⸻ 🔹 Key Difference The main difference between the two: ✔ StringBuffer → Thread-safe (synchronized) ✔ StringBuilder → Not thread-safe (faster in single-threaded environments) In most modern applications, StringBuilder is preferred unless thread safety is required. ⸻ 🔎 Key Takeaway: Use mutable strings when frequent modifications are needed to improve performance and reduce unnecessary object creation. Excited to keep strengthening my Java fundamentals! 🚀 #CoreJava #JavaProgramming #MutableStrings #StringBuilder #StringBuffer #JavaDeveloper #ProgrammingFundamentals #LearningJourney
To view or add a comment, sign in
-
-
📘 Core Java – Day 9 Topic: Pass by Value & Pass by Reference Today I learned how data is passed to methods in Java. Understanding this concept helps avoid confusion while working with variables and objects. 🔹 Pass by Value 🔸 What is Pass by Value? The actual value stored in a variable is passed to a method. Java creates a copy of the value and sends it to the method. Any change made inside the method does not affect the original variable. This ensures data safety and avoids unintended changes. 🔸 Explanation When a primitive data type (like int, float, char, etc.) is passed to a method, Java passes only the value, not the memory address. So, the original variable remains unchanged. 🔸 Example: class PassByValueExample { static void change(int x) { x = 50; // changing copied value } public static void main(String[] args) { int a = 10; change(a); System.out.println(a); } } Output: 10 ✔ Even though x is changed to 50, the original variable a remains 10. 🔹 Pass by Reference (Object Reference) 🔸 What is Pass by Reference? The reference (memory address) of an object is passed to a method. Multiple references can point to the same object. Changes made inside the method affect the original object. This improves memory efficiency. 🔸 Explanation When an object is passed to a method, both the original reference and method parameter point to the same object in memory. So, changes reflect everywhere. 🔸 Example: class Student { int marks; } class PassByReferenceExample { static void update(Student s) { s.marks = 90; // modifying object } public static void main(String[] args) { Student obj = new Student(); obj.marks = 60; update(obj); System.out.println(obj.marks); } } Output: 90 ✔ The object value is updated because both references point to the same memory location. #CoreJava #JavaProgramming #LearningJava #PassByValue #PassByReference #Day9
To view or add a comment, sign in
-
📌 Instance Variable vs Local Variable in Java – In Java, variables are classified based on where they are declared and how long they exist in memory. Two important types are Instance Variables and Local Variables. ✅ 1️⃣ Instance Variable in Java 👉 An instance variable is a variable declared inside a class but outside all methods. It belongs to an object (instance) of the class. 👉 Key Features: 🔹Declared inside class but outside methods 🔹Each object gets separate memory 🔹Scope is entire class 🔹Lifetime is as long as the object exists 🔹Stored in Heap memory... ✅ 2️⃣ Local Variable in Java 👉 A local variable is declared inside a method, constructor, or block. It is used only within that method or block. 👉 Key Features: 🔹Declared inside a method or block 🔹Scope is limited to that method 🔹Lifetime is only while method executes 🔹Must be initialized before use 🔹Stored in Stack memory 🔹Used for temporary calculations 🔹Used to store object properties.. Learning Java variables step by step makes OOP concepts crystal clear! Instance variables store object data, while local variables help in temporary calculations. 🙏 Special thanks to Anand Kumar Buddarapu sir for continuous guidance and support. 🙏A heartfelt thank you to Uppugundla Sairam Sir and Saketh Kallepu Sir for building such an inspiring learning environment , guidance and opportunities you provide make a huge difference in shaping our technical and professional journey. #Java #Variables #InstanceVariable #LocalVariable #JavaBasics #CodingJourney
To view or add a comment, sign in
-
-
☕ Java Generics – Upper Bounded Wildcards Explained In Java Generics, the question mark (?) represents a wildcard, meaning an unknown type. Sometimes, we need to restrict the type of objects that can be passed to a method — especially when working with numbers or specific class hierarchies. That’s where Upper Bounded Wildcards come into play. 🔹 What is an Upper Bounded Wildcard? To restrict a wildcard to a specific type or its subclasses, we use: <? extends ClassName> This means: 👉 Accept ClassName or any of its subclasses. For example, if a method should only work with numeric types, we restrict it to Number and its subclasses like Integer, Double, etc. As explained in the document (Page 1), the syntax uses ? followed by the extends keyword to define the upper bound. 🔹 Practical Example From the example shown (Page 2), a method calculates the sum of elements in a list: public static double sum(List<? extends Number> numberlist) { double sum = 0.0; for (Number n : numberlist) sum += n.doubleValue(); return sum; } 📌 Why ? extends Number? ✔ Ensures only numeric types are allowed ✔ Accepts List<Integer> ✔ Accepts List<Double> ✔ Maintains type safety 🔹 Usage in Main Method List<Integer> integerList = Arrays.asList(1, 2, 3); System.out.println("sum = " + sum(integerList)); List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5); System.out.println("sum = " + sum(doubleList)); 🔹 Output (Page 3) sum = 6.0 sum = 7.0 This demonstrates how the same method works seamlessly with different numeric types. 💡 Upper bounded wildcards improve flexibility while maintaining compile-time type safety. They are essential for writing reusable and robust generic methods in Java. #Java #Generics #UpperBoundedWildcards #JavaProgramming #OOP #FullStackJava #Developers #AshokIT
To view or add a comment, sign in
-
🔹 Understanding Java Streams in Simple Words Java Streams (introduced in Java 8) help process collections in a clean and functional way — without writing complex loops. Instead of writing lengthy code, streams allow us to filter, transform, and process data efficiently. ✅ Example: List numbers = Arrays.asList(1,2,3,4,5,6); List even = numbers.stream() .filter(n -> n % 2 == 0) .toList(); System.out.println(even); ✅ Common Stream Operations with Examples: ✔ filter() → select data List even = numbers.stream() .filter(n -> n % 2 == 0) .toList(); ✔ map() → transform data List doubled = numbers.stream() .map(n -> n * 2) .toList(); ✔ count() → count elements long count = numbers.stream() .filter(n -> n > 3) .count(); ✔ sorted() → sort values List sortedList = numbers.stream() .sorted() .toList(); ✔ reduce() → combine values int sum = numbers.stream() .reduce(0, (a, b) -> a + b); Streams make code more readable, modern, and efficient. If you're learning Java, mastering Streams is a must! #Java #JavaStreams #Programming #Coding #Developers #Learning
To view or add a comment, sign in
-
Remove Duplicates from a List of Strings using Java Streams: Java Streams make it super easy to eliminate duplicates from a list with just one line of code. import java.util.*; import java.util.stream.Collectors; public class RemoveDuplicates { public static void main(String[] args) { List<String> names = Arrays.asList("Java", "Python", "Java", "C++", "Python"); List<String> uniqueNames = names.stream() .distinct() .collect(Collectors.toList()); System.out.println(uniqueNames); } } ✅ Output : [Java, Python, C++,] 💡 Why use distinct()? Removes duplicate elements Maintains insertion order Cleaner and more readable than traditional loops 📌 Pro tip: distinct() internally uses hashCode() and equals() — so it works perfectly for Strings and well-defined objects. #Java #JavaStreams #Coding #Programming #CleanCode #Developers #LearnJava
To view or add a comment, sign in
-
Until now, our Java programs knew all the values in advance. But real programs become useful only when they can listen to the user. Think about real life: 📝 A form is meaningful only when someone fills it. 🏧 An ATM works only after you enter details. A Java program also needs a way to listen 👂. That’s where user input comes in. 🛠️ 𝐔𝐬𝐞𝐫 𝐈𝐧𝐩𝐮𝐭 𝐢𝐧 𝐉𝐚𝐯𝐚 (𝐔𝐬𝐢𝐧𝐠 𝐒𝐜𝐚𝐧𝐧𝐞𝐫) Java provides a built-in class called Scanner to read input from the user while the program is running. There’s a simple flow involved: -->𝘐𝘮𝘱𝘰𝘳𝘵 𝘵𝘩𝘦 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘤𝘭𝘢𝘴𝘴 Before using Scanner, Java must be told where it comes from.This is done using import java.util.Scanner; -->𝘊𝘳𝘦𝘢𝘵𝘦 𝘢 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘰𝘣𝘫𝘦𝘤𝘵 The Scanner object is created using System.in , which means input will be read from the keyboard ⌨️. -->𝘙𝘦𝘢𝘥 𝘶𝘴𝘦𝘳 𝘪𝘯𝘱𝘶𝘵 Different methods are used based on the data type: • nextLine() → text • nextInt() → whole numbers • nextDouble() → decimal values -->𝘜𝘴𝘦 𝘵𝘩𝘦 𝘪𝘯𝘱𝘶𝘵 Once the input is stored in variables, the program can display it, compare it, or apply logic ⚙️. -->𝘊𝘭𝘰𝘴𝘦 𝘵𝘩𝘦 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 Closing the Scanner releases the input resource after the program finishes ✅. This small setup is what transforms a static program into an interactive one ✨. I’ve also attached a simple Java program that takes input from the user and uses it - feel free to go through it for better understanding. #Java #CoreJava #JavaBasics #LearningJourney #Programming #BuildInPublic
To view or add a comment, sign in
-
-
Java Basics: equals() and hashCode() (explained simply) When I first started learning Java, equals() and hashCode() were confusing but sounded very important...but no one explained why😅 Here's the simple idea👇 📍equals() This method checks whether two objects are same. Example: Two *User* objects with the same id are equal. 📍hashCode() This method generates a integer value hashCode which helps Java store and find objects faster in collections like *HashMap* , *HashSet*. ❗The important rule: If two objects are equal using the equals() method, they must return the same hashCode(). ☘️ Sample Example: @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return id == user.id; } @Override public int hashCode() { return Objects.hash(id); } Here id decides the equality hence it is used in both the methods ❌ Common beginner mistakes: Overriding the equals() method but forgot to override the hashCode() method. Result: The hashCode data structure starts behaving strangely. Hard to find bugs. ✔️Bigenner Tip: Use immutable fields Override both the methods together Struggled with this before? Drop a 👍 or comment 👇 #Java #SoftwareEngineering #CleanCode #Programming
To view or add a comment, sign in
-
-
Understanding Map in Java — One of the Most Important Concepts in the Collections Framework The Map interface in Java is a powerful data structure used to store data in key–value pairs, where every key is unique and maps to a specific value. Let’s simplify it: Key Characteristics: - Stores data as Key → Value pairs - Keys must be unique (duplicate keys overwrite values) - Duplicate values are allowed - No indexing — access data using keys Common Map Implementations: - HashMap → Fastest performance (O(1)), no order guarantee - LinkedHashMap → Maintains insertion order - TreeMap → Sorted keys (O(log n)) - ConcurrentHashMap → Thread-safe for multi-threaded applications Most Used Methods: - put() – Add or update data - get() – Retrieve value - remove() – Delete entry - containsKey() – Check key existence - entrySet() – Iterate key-value pairs Interview Tip: - If ordering matters → use LinkedHashMap - If sorting is needed → use TreeMap - If performance matters → use HashMap Java Collections become much easier once you truly understand how Map works. What Map implementation do you use most in your projects #Java #JavaDeveloper #SpringBoot #BackendDevelopment #JavaCollections #Programming #SoftwareDevelopment #Coding #TechLearning
To view or add a comment, sign in
-
-
🔷 TreeSet in Java – 📌 1. What is TreeSet? TreeSet is a class in Java that implements the NavigableSet (SortedSet) interface. It stores unique elements only and maintains them in sorted (ascending) order by default. 👉 No duplicates 👉 Automatically sorted Internally, TreeSet uses a Red-Black Tree (self-balancing binary search tree). ⚙ 2. Internal Data Structure of TreeSet When you add an element: set.add("Java"); Internally: 👉 Element is placed in a Red-Black Tree 👉 Tree keeps elements in sorted order 👉 Tree remains balanced for performance 🧠 Structure Used: • Red-Black Tree • Self-balancing BST This guarantees: ✅ Sorted data ✅ Good performance 🧱 4. Constructors of TreeSet 1️⃣ Default Constructor TreeSet<String> set = new TreeSet<>(); • Natural sorting order 2️⃣ With Comparator (custom sorting) TreeSet<String> set = new TreeSet<>(Collections.reverseOrder()); • Descending order 3️⃣ With Collection TreeSet<String> set = new TreeSet<>(list); • Removes duplicates • Sorts automatically ⭐ 5. Important Characteristics ✔ No duplicate elements ✔ Always sorted ✔ Does NOT allow null (Java 8+) ✔ Not synchronized ✔ Slower than HashSet & LinkedHashSet TAP Academy , Rohit Ravinder , Somanna M G , Sharath R , Ravi Magadum , kshitij kenganavar , Poovizhi VP , Hemanth Reddy #Java #TreeSet #JavaCollections #CoreJava #JavaDeveloper #Programming #Coding #SoftwareDevelopment #TechLearning #DataStructures #LearningJava #DeveloperCommunity
To view or add a comment, sign in
-
More from this author
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development