ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        String a = "hello";
        String c = new String("hello").intern();
        System.out.println(a == c);
    }
}
  1. A. false
  2. B. true
  3. C. Compile-time error: intern() is not a method of String
  4. D. Throws an exception at runtime

Correct answer: B. true

intern() looks up (or adds) the string's content in the string pool and returns the canonical pooled reference. Since "hello" is already pooled from the literal a, c.intern() returns that exact same pooled reference as a, making a == c true.

More OOP with C++ and Java questions

Exams that ask this topic