Comparing strings in Java

Comparing strings in Java

compare, String

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


== 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 Strings to determine whether or not they hold the same value we would recommend using the equals() method.

  1. Implementation of String.equals() first checks for reference equality (using ==), and if the strings are the same by reference, no further calculation is performed!
  2. 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 the String 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.
  3. 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

String fooString1 = new String("foo");
String fooString2 = new String("foo");

fooString1 == fooString2;


//== handles null strings, but calling .equals() from a null string will raise an exception:
String nullString1 = null;
String nullString2 = null;

nullString1 == nullString2;

//Throws Exception


Java String Literals

Java Equals

Java Intern Strings