Explain the difference between == and equals() method.

Beginner

Answer

  • == operator: Compares references for objects (memory addresses) and values for primitives
  • equals() method: Compares the actual content/state of objects (when properly overridden)
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = "hello";
String s4 = "hello";
System.out.println(s1 == s2);        // false (different objects)
System.out.println(s1.equals(s2));   // true (same content)
System.out.println(s3 == s4);        // true (string pool)