Typically programmers become accustom to using the == operator when comparing strings. While this is certainly valid syntax in Java, there is a catch that you should know about.
The Catch
== compares object references
.equals() compares string values
Explained
==
performs a reference equality check, to determine whether the two objects (strings in this case) refer to the same object in the memory.
The equals()
method will check whether the contents of the two objects are the same.
While ==
is faster, there is a chance that the comparison will give false results in some cases. If you were comparing two String
s to determine whether or not they hold the same value we would recommend using the equals()
method.
- Implementation of
String.equals()
first checks for reference equality (using==
), and if the strings are the same by reference, no further calculation is performed! - If the string references are not the same,
String.equals()
will next check the lengths of the strings. This is also a fast operation because theString
class stores the length of the string, no need to count the characters. If the lengths differ, no further check is performed, we know they cannot be equal. - Only if we got this far will the contents of the 2 strings be actually compared, and this will be a short-hand comparison: not all the characters will be compared, if we find a mismatching character (at the same position in the 2 strings), no further characters will be checked.
Below we have a few examples of using both the .equals and == operators. We hope this post helps you on your journey in Java string comparison.
Code Example
//Init String fooString1 = new String("foo"); String fooString2 = new String("foo"); //False fooString1 == fooString2; //True fooString1.equals(fooString2); //== handles null strings, but calling .equals() from a null string will raise an exception: String nullString1 = null; String nullString2 = null; //True nullString1 == nullString2; //Throws Exception nullString1.equals(nullString2);