ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
// in main:
String a = "hello";
String b = "hello";
String c = new String("hello");
String d = c.intern();
System.out.println((a == b) + " " + (a == c) + " " + (a == d));
  1. A. true false true
  2. B. true true true
  3. C. false false false
  4. D. true false false

Correct answer: A. true false true

String literals are pooled: a and b refer to the same interned object, so a == b is true. `new String(...)` always creates a distinct heap object outside the pool, so a == c is false. intern() returns the canonical pooled reference, which is the same object as the literal, so a == d is true.

More OOP with C++ and Java questions

Exams that ask this topic