ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
final String a = "Ja";
String b = "Ja";
String x = a + "va";
String y = b + "va";
String z = y.intern();
System.out.print((x == "Java") + " " + (y == "Java") + " "
    + (z == "Java") + " " + y.equals(x));
  1. A. true true true true
  2. B. false false true true
  3. C. true false true true
  4. D. false false false true

Correct answer: C. true false true true

Because a is a final local variable initialised with a constant, a + "va" is a compile-time constant expression; it is folded to "Java" and taken from the string pool, so x == "Java" is true. b is not final, so b + "va" is computed at run time into a new String object: false. intern() returns the pooled instance: true. equals compares contents, so y.equals(x) is true.

More OOP with C++ and Java questions

Exams that ask this topic