What is the output of the Java code final String x = “a”; String y = x + “b”; System.out.println(y == “ab”);?
Correct answer B. true
Explanation
Because x is a final variable initialised with a constant, x + "b" is a constant expression evaluated by the compiler. Constant strings are interned, so y and the literal "ab" refer to one object and == gives true. Without final, the concatenation would happen at run time, produce a new object and print false.
Answer checked How we write and check questions
Discussion