String Comparison in Java — Java Technical Interview Questions & Answers
String Comparison in Java
String Comparison in Java
- == compares references (same object in memory). equals compares characters. new String("Hi") twice → == is false, equals is true.
- Literals "Hi" == "Hi" can be true because of the String Pool. User input and new String(...) almost never match with ==. Always equals for content.
- equalsIgnoreCase ignores capital letters. compareTo gives ordering, not just true/false.
- Let's take this on the board with one tiny Main class — no extra files. String Comparison in Java — output: false then true. new String("Hi") twice = two objects (== false). equals checks the text Hi. Start from main, go line by line, and stop at each print. That output is the proof for String Comparison.
new String("Hi") new String("Hi")
│ │
└─ == false
└─ equals trueTechnical Interview Tip: Show new String("Hi") twice: == false, equals true. That is the whole answer.
Code Examples for String Comparison in Java
Example
public class Main {
public static void main(String[] args) {
String a = new String("Hi");
String b = new String("Hi");
System.out.println(a == b); // false (refs)
System.out.println(a.equals(b)); // true (content)
}
}String Comparison in Java — output: false then true. new String("Hi") twice = two objects (== false). equals checks the text Hi.
How to Explain String Comparison in Java to an Interviewer
== vs equals on String?
== references equals content
Two new String("Hi")?
== false equals true