ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
// in main:
String s1 = "Java";
String s2 = new StringBuilder("Java").toString();
System.out.println((s1 == s2) + " " + s1.equals(s2) + " " + (s1 == s2.intern()));
  1. A. false true true
  2. B. true true true
  3. C. false false true
  4. D. false true false

Correct answer: A. false true true

s2 is built via StringBuilder.toString(), which always allocates a fresh String object outside the pool, so s1 == s2 is false. Their contents are identical so equals() is true. s2.intern() returns the pooled reference equal to the literal s1, so s1 == s2.intern() is true.

More OOP with C++ and Java questions

Exams that ask this topic