Hiprup

What is the difference between == and .equals() in Java?

The two operators look similar but compare different things.

== operator — compares references (memory addresses) for objects, and values for primitives. Two new String("a") objects return false.

.equals() method — compares logical content. Default in Object is reference equality, but classes like String, Integer, and collections override it for value equality.

Rule — use == for primitives and reference identity; use .equals() for object content. Always override hashCode() when overriding equals().

String s1 = "hello";        // String pool
String s2 = "hello";        // Same pool reference
String s3 = new String("hello"); // New object on heap

System.out.println(s1 == s2);      // true  (same pool reference)
System.out.println(s1 == s3);      // false (different objects)
System.out.println(s1.equals(s3)); // true  (same content)

// Integer caching (-128 to 127)
Integer a = 127;
Integer b = 127;
System.out.println(a == b);  // true  (cached)

Integer c = 128;
Integer d = 128;
System.out.println(c == d);  // false (not cached, different objects)
System.out.println(c.equals(d)); // true  (same value)

String literals are interned — s1 and s2 reference the same pool object (== true). new String creates a separate heap object (== false with pool strings). .equals compares content regardless of memory location. Integer caching causes a subtle gotcha: values -128 to 127 are cached (== true), but 128+ creates new objects (== false).

The Integer caching gotcha (-128 to 127) is a classic interview question. Always mention the equals/hashCode contract.

The String pool behavior explains why == sometimes works for Strings (misleading beginners).

What is the difference between == and .equals() in Java? | Hiprup