Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

What is printed? (Java: == vs equals on Strings)

What is printed? (Java: == vs equals on Strings)
String a = "hello";
String b = "hel" + "lo";
String c = new String("hello");
String d = c.intern();
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c) + " " + (a == d));
  1. A. true true true true
  2. B. false false true true
  3. C. true false true true
  4. D. true false true false

Correct answer: C. true false true true

"hel" + "lo" is a compile-time constant, so it refers to the same pooled literal as a. new String creates a distinct object (== false, equals true). intern() returns the pooled instance, so a == d. Always compare contents with equals.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic