Sobes.tech
Intern — Senior

String comparison in Java considering interning and concatenation

livecode

Task condition

Determine which of the string reference comparisons below will return true. When answering, consider how the compiler handles string literals, the interning mechanism, and the characteristics of string concatenation in Java.

var a = "{ between braces }";
final String b = "{ between ";
String c = "braces }";
String d = "{ between braces }";
String e = new String("{ between braces }");

System.out.println(a == d);                    // #1
System.out.println(a == b + c);                // #2
System.out.println(a == b + "braces }");      // #3
System.out.println(a == e);                    // #4

For each comparison, explain why the result is as it is: whether the compared object is the same object in the string pool, whether a new object is created as a result of concatenation, and how the new operator affects interning.