What is the difference between == and .equals() in Java, and when should I use each?
0

I'm learning how Java handles object comparison. I understand that == checks for reference equality, while .equals() can be overridden to check logical equality. Can someone provide practical examples of when to use each, especially with Strings and custom objects?


Anonymous May 31, 2025 09:45 81 views

1 Answer

0

🚀 Java Interview Essential: == vs .equals() Method
This is one of the most important questions for entry-level Java interviews!

📋 Key Differences:
1. Nature
== is an operator
.equals() is a method


2. What They Compare
== operator checks object references (memory addresses)
.equals() method checks content/values

Example

String nameOfOwner = "Yuvraj";                    // String literal
String nameOfRental = new String("Yuvraj");       // New object

// Reference comparison using ==
System.out.println(nameOfOwner == nameOfRental);        // Output: false

// Content comparison using .equals()
System.out.println(nameOfRental.equals(nameOfOwner));   // Output: true    

🔍 Why This Happens:

  • String literals are stored in the String Pool (same reference for identical values)
  • new String() creates a new object in heap memory (different reference)
  • .equals() compares the actual character sequences

⚠️ Important Interview Points:
3. Memory Allocation    
String a = "Hello";           // String pool
String b = "Hello";           // Same reference as 'a'
String c = new String("Hello"); // New object in heap

System.out.println(a == b);     // true (same reference)
System.out.println(a == c);     // false (different references)
System.out.println(a.equals(c)); // true (same content)

4. Null Safety
String str1 = null;
String str2 = "Hello";

// Dangerous - can throw NullPointerException
// str1.equals(str2);

// Safe approaches:
System.out.println(Objects.equals(str1, str2));  // false
System.out.println("Hello".equals(str1));        // false (no exception)

🏆 Pro Tips:

  • Always use .equals() for String comparisons
  • Use Objects.equals() for null-safe comparisons
  • Remember: "If .equals() returns true, hashCode() must be the same"

armandeveloper Jul 4, 2025 14:51
You need to sign in to post an answer.
Need More Help?

Get personalized assistance with your technical questions.