Equality and String behaviour in Java
How == differs from equals(), why String is immutable, and how the string pool changes comparison results.
Many Java screening questions hinge on one idea: a variable of a reference type holds a reference to an object, not the object itself. Once that is clear, questions about ==, equals() and String become predictable.
== compares references, equals() compares content
For primitives such as int and double, == compares values. For objects, == checks whether two references point to the same object in memory. The equals() method is meant to compare content, and classes like String, Integer and ArrayList override it to do that.
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b); // true, same pooled literal
System.out.println(a == c); // false, c is a new object
System.out.println(a.equals(c)); // true, same characters
String literals with the same text share one object in the string pool, which is why a == b is true. Using new always creates a separate object. In real code, always compare strings with equals().
Strings are immutable
No String method changes the original object. Methods like concat(), toUpperCase() and replace() return a new String. If you ignore the return value, nothing changes.
String s = "data";
s.toUpperCase();
System.out.println(s); // data
s = s.toUpperCase();
System.out.println(s); // DATA
When you need to build a string inside a loop, use StringBuilder, which is mutable and avoids creating many temporary objects.
Concatenation runs left to right
The + operator is evaluated left to right. While both sides are numbers it adds them; once one side is a String, it joins text from that point on.
System.out.println(1 + 2 + "3"); // 33
System.out.println("1" + 2 + 3); // 123
Remember that *, / and % still bind more tightly than +, so "x" + 2 * 3 gives x6.
A quick checklist for output questions
- Is the comparison on primitives or on objects?
- Was each object created from a literal or with
new? - Is the return value of a String method actually assigned?
- Where does the first String appear in a
+chain?
More in Programming