ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = new String("hello");
        System.out.println((a == b) + " " + (a == c) + " " + a.equals(c));
    }
}
  1. A. true true true
  2. B. false false true
  3. C. true false true
  4. D. true true false

Correct answer: C. true false true

String literals are interned in the string pool, so a and b refer to the same pooled object (a == b is true). new String("hello") explicitly allocates a fresh heap object distinct from the pool, so a == c is false. equals() compares contents, which are identical, so a.equals(c) is true.

More OOP with C++ and Java questions

Exams that ask this topic