I’ve been using the ==
operator to compare strings in my program, but I encountered a bug. After switching to .equals()
, the issue was resolved.
What is the difference between ==
and .equals()
when comparing strings in Java? Is using ==
for string comparison a bad practice, and in what scenarios should each be used?
The key difference between == and .equals() when comparing strings in Java is what they compare:
== (Reference Comparison) → Checks if two string variables point to the same memory location.
.equals() (Value Comparison) → Checks if two strings have the same sequence of characters, regardless of memory location.
Example:
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); // true (both reference the same literal in the string pool)
System.out.println(s1 == s3); // false (s3 is a new object)
System.out.println(s1.equals(s3)); // true (same content)
When checking if two variables refer to the exact same object (e.g., singleton patterns or interned strings).
Example:
String a = "Java";
String b = "Java";
System.out.println(a == b); // true (string pool optimization)
However, this only works for string literals. If you’re dealing with dynamically created strings, == can fail.
When should you use .equals()?
Always use .equals() for actual string content comparison.
Example:
String a = "Java";
String b = new String("Java");
System.out.println(a.equals(b)); // true (content is the same)
.equals() ensures correctness regardless of how the string was created.