ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        String a = new String("hi").intern();
        String b = "hi";
        System.out.print(a == b);
    }
}
  1. A. false
  2. B. Compilation error: intern() returns Object
  3. C. true
  4. D. It is undefined, depends on garbage collection timing

Correct answer: C. true

intern() looks up (or adds) the string in the JVM's string pool and returns that canonical pooled reference. Since the literal "hi" is already pooled, a.intern() returns the exact same reference as b, so a == b is true.

More OOP with C++ and Java questions

Exams that ask this topic