Junior — Senior
String comparison in Java: interning, synchronization, and the results of the == operators
livecode
Task condition
Analyze what output the program will produce and why. Explain the differences between variables a, a1, a2, and a3, where string interning occurs, and whether strings can be used as monitors for synchronization. What potential issues might arise from this approach?
public class StringQuiz {
public static void main(String[] args) {
String a = "aaaa";
String a1 = "aaaa";
String a2 = new String("aaaa");
String a3 = String.valueOf(new String("aaaa"));
System.out.println(a == a1); // ?
System.out.println(a == a2); // ?
System.out.println(a == a3); // ?
}
}
What needs to be explained:
- Why
a == a1returnstrue(both references point to the same interned string). - Why
a == a2returnsfalse(the object is created withnew, resides in heap, not interned). - Why
a == a3is alsofalse–String.valueOfcreates a new string, not using the already interned constant. - Where exactly in the code interning occurs (when the literal
"aaaa"is loaded). - Is synchronization on the
Stringobject (synchronized (a) { ... }) possible? Discuss that it is technically permissible but can lead to unpredictable conflicts, as identical literals in different parts of the program may refer to the same object, creating hidden locks between independent code sections. - What safer alternatives exist (using a separate mutex object).