Why should you not use the == operator to compare two Strings for equality What should you use instead?

In order to compare Strings for equality, you should use the String object’s equals or equalsIgnoreCase methods. We will also see why we should not use the == operator to compare strings.

Comparing Strings with equals() Method

If we need to compare two strings in java and also care about the casing of the strings we can use the equals() method.

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

public class CompareTwoStrings { public static void main(String[] args) { String firstString = "Test123"; String secondString = "Test" + 123; String thirdString = "TEST123"; if (firstString.equals(secondString)) { System.out.println("first and second strings are equal"); } if (firstString.equals(thirdString)) { System.out.println("first and third string are equal"); } } }

Output:

first and second strings are equal

Comparing Strings with equalsIgnoreCase() Method

If we need to compare two strings in java but don’t care about the casing of the strings we can use the equalsIgnoreCase() method.

For example, in the above code snippet, if we replaced .equals() with .equalsIgnoreCase() method, then both print statements get executed:

public class CompareTwoStrings { public static void main(String[] args) { String firstString = "Test123"; String secondString = "Test" + 123; String thirdString = "TEST123"; if (firstString.equalsIgnoreCase(secondString)) { System.out.println("first and second strings are equal"); } if (firstString.equalsIgnoreCase(thirdString)) { System.out.println("first and third string are equal"); } } }

Output:

first and second strings are equal first and third string are equal

Do not use the == operator to compare Strings

Note: When comparing two strings in java, we should not use the == or != operators.

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.

public class CompareTwoStrings { public static void main(String[] args) { String firstString = "Test123"; String secondString = "Test123"; String thirdString = new String("Test123"); if (firstString == secondString) { System.out.println("first and second strings are equal"); } if (firstString == thirdString) { System.out.println("first and third strings are equal"); } } }

Output:

first and second strings are equal

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.

For example:

"baz".equals(foo)

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

A more readable alternative is to use Objects.equals(), which does a null check on both parameters:

e.g. Objects.equals(foo, "baz").

Comparing Strings in a Switch Statement

As of Java 1.7, it is possible to 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.

public class CompareTwoStrings { public static void main(String[] args) { String stringToSwitch = "A"; switch (stringToSwitch) { case "a": System.out.println("a"); break; case "A": System.out.println("A"); //the code goes here break; case "B": System.out.println("B"); break; default: break; } } }

Conclusion

In this post we explained how to compare strings in java with code examples. When casing of the strings matters, we should use .equals() and when casing is not important, then we should use .equalsIgnoreCase().

Moreover, we should not use the == operator to compare strings, as the == operator checks the reference and not the value.

View Discussion

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Like Article

    Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.
    Whenever we create an object using the operator new, it will create a new memory location for that object. So we use the == operator to check memory location or address of two objects are the same or not.

    In general, both equals() and “==” operators in Java are used to compare objects to check equality, but here are some of the differences between the two: 

    1. The main difference between the .equals() method and == operator is that one is a method, and the other is the operator.
    2. We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
    3. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method. See Why to Override equals(Object) and hashCode() method ? in detail.

    public class Test {

        public static void main(String[] args)

        {

            String s1 = "HELLO";

            String s2 = "HELLO";

            String s3 =  new String("HELLO");

            System.out.println(s1 == s2);

            System.out.println(s1 == s3);

            System.out.println(s1.equals(s2));

            System.out.println(s1.equals(s3));

        }

    }

    Output true false true true

    Explanation: Here, we create two objects, namely s1 and s2. 

    • Both s1 and s2 refer to same objects.
    • When we use the == operator for s1 and s2 comparison, the result is true as both have the same addresses in the string constant pool.
    • Using equals, the result is true because it’s only comparing the values given in s1 and s2.

                                                                                                               Java String Pool

    s1 = “HELLO”

    s2 = “HELLO”

                                                                                                                  Java Heap

    Let us understand both the operators in detail:

    Equality operator(==)

    We can apply equality operators for every primitive type, including the boolean type. We can also apply equality operators for object types. 

    class Test {

        public static void main(String[] args)

        {

            System.out.println(10 == 20);

            System.out.println('a' == 'b');

            System.out.println('a' == 97.0);

            System.out.println(true == true);

        }

    }

    Output false false true true

    If we apply == for object types then, there should be compatibility between arguments types (either child to parent or parent to child or same type). Otherwise, we will get a compile-time error. 

    class Test {

        public static void main(String[] args)

        {

            Thread t = new Thread();

            Object o = new Object();

            String s = new String("GEEKS");

            System.out.println(t == o);

            System.out.println(o == s);

           System.out.println(t==s);

        }

    }

    Output: 

    false false // error: incomparable types: Thread and String

    .equals() Method

    In Java, the String equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are the same, it returns true. If all characters are not matched, then it returns false. 

    public class Test {

        public static void main(String[] args)

        {

            Thread t1 = new Thread();

            Thread t2 = new Thread();

            Thread t3 = t1;

            String s1 = new String("GEEKS");

            String s2 = new String("GEEKS");

            System.out.println(t1 == t3);

            System.out.println(t1 == t2);

            System.out.println(s1 == s2);

            System.out.println(t1.equals(t2));

            System.out.println(s1.equals(s2));

        }

    }

    Output true false false false true

    Explanation: Here, we are using the .equals method to check whether two objects contain the same data or not. 

    • In the above example, we create 3 Thread objects and 2 String objects.
    • In the first comparison, we check whether t1 == t3 or not. As we know that both t1 and t3 point to the same object. That’s why it returns true.
    • In the second comparison, we are using the operator “==” for comparing the String Objects and not the contents of the objects. Here, both the objects are different, and hence the outcome of this comparison is “False.”
    • When we are comparing 2 String objects by .equals() operator, then we are checking that is both objects contain the same data or not.
    • Both the objects contain the same String, i.e., GEEKS. That’s why it returns true.

    This article is contributed by Veturi Lakshmi Prathyusha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.