Comparing Strings


In order to compare Strings for equality, you should use the String object's equals or equalsIgnoreCase methods.

For example, the following snippet will determine if the two instances of String are equal on all characters:

class ComparingStrings
{
    public static void main(String[] args) throws java.lang.Exception
    {
        String firstString = "Hello123";
        String secondString = "Hello" + 123;
        if (firstString.equals(secondString))
	{
            System.out.print("Equal");
        }
    }
}

This example will compare them, independent of their case

class ComparingStrings
{
    public static void main(String[] args) throws java.lang.Exception
    {
        String firstString = "Hello123";
        String secondString = "HELLO123";
        if (firstString.equalsIgnoreCase(secondString))
	{
            System.out.print("Equal"); // Both Strings are equal, ignoring the case of the individual characters.
 
        }
    }
}

Note that equalsIgnoreCase does not let you specify a Locale. For instance, if you compare the two words "Coding" and "CODING" in English they are equal; however, in Turkish they are different (in Turkish, the lowercase I is ı). For cases like this, converting both strings to lowercase (or uppercase) with Locale and then comparing with equals is the solution.

class ComparingStrings
{
    public static void main(String[] args) throws java.lang.Exception
    {
        String firstString = "Coding";
        String secondString = "CODING";
        System.out.println(firstString.equalsIgnoreCase(secondString)); // prints true
 
        Locale locale = Locale.forLanguageTag("en-US");
        System.out.println(firstString.toLowerCase(locale).equals(secondString.toLowerCase(locale))); // prints false
    }
}

Do not use the == operator to compare Strings

Unless you can guarantee that all strings have been interned (see below), you should not use the == or != operators to compare Strings. These operators actually test references, and since multiple String objects can represent the same String, this is liable to give the wrong answer.

Instead, use the String.equals(Object) method, which will compare the String objects based on their values. For a detailed explanation, please refer to Pitfall: using == to compare strings.

Comparing Strings in a switch statement

Compare a String variable to literals in a switch statement. Make sure that the String is not null, otherwise it will always throw a NullPointerException. Values are compared using String.equals, i.e. case sensitive.

class ComparingStrings
{
	public static void main(String[] args) throws java.lang.Exception
	{
		String stringToSwitch = "C";
 
		switch (stringToSwitch)
		{
			case "c":
				System.out.println("c");
				break;
			case "C":
				System.out.println("C"); // This line will be executed
				break;
			case "D":
				System.out.println("D");
				break;
			default:
				break;
		}
	}
}

Comparing Strings with constant values

When comparing a String to a constant value, you can put the constant value on the left side of equals to ensure that you won't get a NullPointerException if the other String is null.

"baz".equals(bar); // Evaluates to false

While baz.equals(bar) will throw a NullPointerException if foo is null, "bar".equals(baz) will evaluate to false.

String orderings

The String class implements Comparable<String> with the String.compareTo method (as described at the start of this example). This makes the natural ordering of String objects case-sensitive order. The String class provide a Comparator<String> constant called CASE_INSENSITIVE_ORDER suitable for case-insensitive sorting.

Comparing with interned Strings

This means it is safe to compare references to two string literals using ==. Moreover, the same is true for references to String objects that have been produced using the String.intern() method.

For example:

String strObject = new String("TutorJoes!");
String string = "TutorJoes!";
 
// Comparing the content of two strings
if (strObject.equals(string))
{
	System.out.println("The strings are equal");
}
 
// Verifying if the two string references are pointing to different objects
if (strObject != string)
{
	System.out.println("The strings are not the same object");
}
 
// Interning a string equal to a literal creates a string with the same reference as the literal
String internedString = strObject.intern();
if (internedString == string)
{
	System.out.println("The interned string and the literal are the same object");
}

Behind the scenes, the interning mechanism maintains a hash table that contains all interned strings that are still reachable. When you call intern() on a String, the method looks up the object in the hash table:

  • If the string is found, then that value is returned as the interned string.
  • Otherwise, a copy of the string is added to the hash table and that string is returned as the interned string.

It is possible to use interning to allow strings to be compared using ==. However, there are significant problems with doing this; see Pitfall - Interning strings so that you can use == is a bad idea for details. It is not recommended in most cases.

Basic Programs