Question

How do I compare two strings?

Answer

A common error that we all make from time to time is incorrect String comparison. Even once you learn how to compare strings correctly, it's extremely easy to make a mistake and use the == operator.

When we compare primitive data types, such as two ints, two chars, two doubles, etc. we can use the == operator. We can also use the == operator to compare two objects. However, when used with an object, the == operator will only check to see if they are the same objects, not if they hold the same contents.

This means that code like the following will not correctly compare to strings :

if ( string1 == string2 )
{
	System.out.println ("Match found");
}

This code will only evaluate to true if string1 and string2 are the same object, not if they hold the same contents. This is an important distinction to make. Checking, for example, to see if
aString == "somevalue", will not evaluate to true even if aString holds the same contents.

To correctly compare two strings, we must use the .equals method(). This method is inherited from java.lang.Object, and can be used to compare any two strings. Here's an example of how to correctly check a String's contents :

if ( string1.equals("abcdef") )
{
	System.out.println ("Match found");
}

This is a simple, and easy to remember tip that will safe you considerable time debugging applications. Remember - never use the == operator if you only want to compare the string's contents.


Back