ProgrammingHardWipro · Cognizant 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.print((a == b) + " " + (a == c) + " " + a.equals(c));
    }
}
  1. A. true true true
  2. B. true false false
  3. C. true false true
  4. D. false false true

Correct answer: C. true false true

String literals are interned, so a and b refer to the same object in the string pool: a == b is true. new String("hello") always creates a distinct heap object outside the pool, so a == c is false, even though the characters are identical, so a.equals(c) is true.

More OOP with C++ and Java questions

Exams that ask this topic