.equals() Vs ==

== (Double Equals)

  • Compares object references (i.e., memory addresses).
  • Checks if two references point to the same object in memory.

String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1 == s2);  // false (different objects)


.equals()

  • Compares object contents (i.e., values).
  • Can be overridden by classes like String, Integer, etc., to compare actual data.
System.out.println(s1.equals(s2));  // true (same content)

🧠 Summary Table:

Comparison == .equals()
Type Reference comparison Content/value comparison
Customizable ❌ (built-in) ✅ (can override in your class)
Common use Primitive types, identity check Comparing String, custom objects

🔥 Bonus:

For primitives like int, == compares values directly:

int a = 10;
int b = 10;
System.out.println(a == b); // true
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.