What does this print?
String a = new String("hi");
String b = new String("hi");
System.out.println((a == b) + " " + a.equals(b));Options
- true true
- true false
- false true (Correct option)
- false false
Answer
false true
Why
For objects, == compares references: are both variables pointing to the exact same object in memory? new String(...) always creates a new object, so a == b is false.
.equals() compares the content. Both strings contain "hi", so it is true.
Rule: use .equals() to compare text and other objects; use == for primitives and for checking null.
Remember
== compares references, equals() compares content.