String Equals vs == Operator Example in Java
On this page (8sections)
Introduction
Comparing strings is one of the most common tasks in Java, but beginners often confuse the == operator with the equals() method. This program demonstrates both and explains when each is appropriate.
Key Difference
| Operator / Method | Compares |
|---|---|
== | Whether two references point to the same object in memory |
equals() | Whether two strings have the same character sequence |
equalsIgnoreCase() | Same as equals() but ignores letter case |
Example Program
public class StringCompareDemo {
public static void main(String[] args) {
String a = new String("Java");
String b = new String("Java");
String c = "Java";
String d = "Java";
System.out.println("a == b : " + (a == b));
System.out.println("a.equals(b) : " + a.equals(b));
System.out.println("c == d : " + (c == d));
System.out.println("c.equals(d) : " + c.equals(d));
String s1 = "hello";
String s2 = "HELLO";
System.out.println("s1.equals(s2) : " + s1.equals(s2));
System.out.println("s1.equalsIgnoreCase(s2) : " + s1.equalsIgnoreCase(s2));
}
}
Sample Output
a == b : false
a.equals(b) : true
c == d : true
c.equals(d) : true
s1.equals(s2) : false
s1.equalsIgnoreCase(s2) : true
How It Works
new String("Java")creates distinct objects on the heap, soa == bisfalseeven though the text matches.- String literals
"Java"are interned in the string pool;canddrefer to the same pooled object, soc == distrue. - For content comparison, always prefer
equals()orequalsIgnoreCase().
Best Practices
- Use
equals()for almost all String content checks. - Use
Objects.equals(a, b)when either operand may benull. - Never use
==to compare user-entered or dynamically built strings.
Common Mistakes
- Using
==after reading input withScannerand expecting content equality. - Calling
equals()on a literal with a possibly-null variable — reverse the call:"fixed".equals(variable).
Frequently Asked Questions
Does == compare string characters in Java?
No. == compares object references (memory addresses). Two String variables can point to different objects with the same text, so == may return false even when the content matches.
When should I use equalsIgnoreCase()?
Use equalsIgnoreCase() when comparing user input or case-insensitive identifiers such as command names or email domains.