Comparing strings with == and equals — Aptitude Question
Comparing strings with == and equals: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 75 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
String a = "code";
String b = "code";
String c = new String("code");
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c));
}
}Options
- true true true
- true false true
- false false true
- true false false
Show the answer and the worked solution
Correct answer: B. true false true
Worked solution
- a and b are both the literal "code", which the compiler places in the string pool once, so a == b compares two references to the same object and is true.
- new String("code") deliberately builds a separate object, so a == c compares different references and is false.
- equals compares contents rather than references, so a.equals(c) is true, and the output is true false true.
Answer: true false true.
The idea
== on objects asks whether two references point at the same object; equals asks whether the contents match. String literals are interned, which is why the first comparison surprises people.
Shortcut. equals compares contents, so the third value is true; new String always makes a fresh object, so a == c is false; pooled literals make a == b true.
Common trap. "false false true" assumes == on two separately declared Strings always compares different objects, missing that identical literals are interned as one.
All Programming Fundamentals questions · placement mock tests