Comparing two Strings in Java

String comparison is one of the essential usages of Strings in Java. Some of the use cases include but not limited to:

1.User authentication-checking validity of passed in username and password in log in screens/forms .

2.Parameter value checking to determine which decision block to execute-e.g after reading a parameter from a properties file or method argument ,the parameter(if a String) depending on its value, determines which block of code to execute e.g. if ‘execMode’ is ‘SYNC’  process synchronously or else if  ‘ASYNC’ process asynchronously.

There are several ways of comparing two Strings which are discussed in detail in this tutorial.

1.Using ‘==’ operator

The == operator checks for reference and not actual values. It is not best practice to check  String equality this way as you will be checking whether the two String objects point to the same reference rather than contain the same values.

However, if the two Strings are initialized by literals and the literals are equal in content composition(including same character case), then the Strings are equal as they point to same String in the String pool(i.e check by ‘==’ will return true)

Example 1

package devsought;

public class StringCompare1 {

    public static void main(String... args) {

        String one="Java";

        String two =new String("Java");

        System.out.println(one==two);       

    }

}

The above program outputs

false

Example 2(both String initialized as literals)

package devsought;

public class StringCompare2 {

    public static void main(String... args) {

        String one="Java";

        String two ="Java";

        System.out.println(one==two);       

    }

}

The above program outputs

true

 

Example 3(Strings initialized by String constructor)

package devsought;

public class StringCompare3 {

    public static void main(String... args) {

        String one = new String("Java");

        String two = new String("Java");

        System.out.println(one == two);

    }

}

The above program outputs

false

Explanation

In Example 1,String one is initialized as a literal whereas String two is initialized as an object.These two objects point to different locations as String one is in the String pool whereas String two is in the heap.

In Example 2,both String one and String two are in the String pool. Since the content of both is the same,String two just reuses what is already in the pool therefore in this instance, comparison using the ‘==’ works.

In Example 3,though both objects contain the same content, the output is false as the objects are allocated different memory address references.

Tip:Do NOT use ‘==’ equality to check for two String object equality in the sense if matching content equality as its used to check address reference equality and not content equality.

2.Using String equals method

This String method compares two Strings for content equality.

Signature: public boolean equals(Object anotherObject)

Usage

strone.equals(strtwo) will return true if strone and  strtwo are  non-null reference values and both point to objects with the same sequence of characters(same content) and same case.If the passed in argument(anotherObject) is null then false is returned.

Example4

package devsought;

public class StringCompare4 {

    public static void main(String... args) {

        String one = new String("Java");

        String two = new String("Java");

        String three = new String("Java8");

        String four = null;

        String five = "Java";

        String six = "JAva";

        System.out.println(one.equals(two));

        System.out.println(one.equals(three));

        System.out.println(two.equals(four));

        System.out.println(one.equals(five));

        System.out.println(one.equals(six));

        System.out.println("a".equals("b"));

 

    }

 

}

The above program outputs

true

false

false

true

false

false

Explanation-the String.equals(Object arg) method compares for equality and will return true if arg is non-null and contains same character sequence as this String object.

3.Using String equalsIgnoreCase Method

Method signature : public boolean equalsIgnoreCase(String anotherString)

This returns true if the passed in argument(anotherString) is non-null and has the same sequence of characters as this String without regard to case.

Example 5

package devsought;

public class StringCompare5 {

    public static void main(String... args) {

        String one = new String("Java");

        String two = new String("Java");

        String three = new String("Java8");

        String four = null;

        String five = "Java";

        String six = "JAva";

        System.out.println(one.equalsIgnoreCase(two));

        System.out.println(one.equalsIgnoreCase(three));

        System.out.println(two.equalsIgnoreCase(four));

        System.out.println(one.equalsIgnoreCase(five));

        System.out.println(one.equalsIgnoreCase(six));

    }

}

 

The above program outputs

true

false

false

true

true

4.Using Objects equals() method

Signature:  public static boolean equals(Object a, Object b)

The Objects class (in the java.util package) (not Object) equals method compares two Strings for equality and returns true when both arguments a and b are equal or when both arguments are null.If one of the arguments is null and the other non-null,then false is returned.If not so,equality is determined by a.equals(b).

Walkthrough:We dissect above statement by looking at the implementation of  the Objects.equals method in the java.util package

public static boolean equals(Object a, Object b) {

        return (a == b) || (a != null && a.equals(b));

    }

1.If a and b are both null,we return true since they point to same location in memory as null is the default value for all references.

2.If only a is null,(a==b) returns false,  (a != null && a.equals(b) also returns false therefore overally false is returned.

3.If only b is null,same logic as above applies.

4.If both a and b are not null

  (a) If a and b are Strings initialized by String constructor,they point to different memory references and (a==b) returns false.The check goes to second portion  (a != null && a.equals(b) whereby the check is by equals method (a.equals(b)),if they contain same character sequence in same character case ,true is returned else false is returned.

(b)If a and b are String literals with same character sequence,then (a==b) true is returned.If they are literals with different character sequences,then overally a false is returned by both equality checks.

Example 6

package devsought;

import java.util.Objects;

public class StringCompare6 {

    public static void main(String... args) {

        String one = new String("Java");

        String two = new String("Java");

        String three = new String("Java8");

        String four = null;

        String five = "Java";

        String six = "JAva";

        System.out.println(Objects.equals(one, two));

        System.out.println(Objects.equals(one, three));

        System.out.println(Objects.equals(two, four));

        System.out.println(Objects.equals(one, five));

        System.out.println(Objects.equals(one, six));

        System.out.println(Objects.equals(four, one));

        System.out.println(Objects.equals(one, four));

        System.out.println(Objects.equals(one, five));

        System.out.println(Objects.equals("Java", "JavA"));

        System.out.println(Objects.equals("Java", one));

        System.out.println(Objects.equals("Java", "Java"));

        System.out.println(Objects.equals("Java", null));

 

    }

}

The above program outputs

true

false

false

true

false

false

false

true

false

true

true

false

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.