I’ve been using the ==
operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals()
instead, and it fixed the bug.
Is ==
bad? When should it and should it not be used? What’s the difference?
==
tests for reference equality (whether they are the same object)..equals()
tests for value equality (whether they are logically “equal”).Objects.equals() checks for
null
before calling.equals()
so you don’t have to (available as of JDK7, also available in Guava).Consequently, if you want to test whether two strings have the same value you will probably want to use
Objects.equals()
.You almost always want to use
Objects.equals()
. In the rare situation where you know you’re dealing with interned strings, you can use==
.From JLS 3.10.5. String Literals:
Similar examples can also be found in JLS 3.10.5-1.
Other Methods To Consider
String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.
String.contentEquals() compares the content of the
String
with the content of anyCharSequence
(available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.