Sobes.tech
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:

  1. Why a == a1 returns true (both references point to the same interned string).
  2. Why a == a2 returns false (the object is created with new, resides in heap, not interned).
  3. Why a == a3 is also falseString.valueOf creates a new string, not using the already interned constant.
  4. Where exactly in the code interning occurs (when the literal "aaaa" is loaded).
  5. Is synchronization on the String object (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.
  6. What safer alternatives exist (using a separate mutex object).