Best way to compare strings in Java


In Java, strings are the reference type. So we can not compare two strings using the == operator as it compares references (will only return true when both references are of the same object).

In Java, all objects are derived from class Object which has one method equals, which is used to compare equality of two object’s values.

See below code this will give you more clearly.

public static void main(String[] args) {
	// These two have the same value
	String str = new String("test");
	
	System.out.println(str.equals("test")); // --> true 

	// ... but they are not the same object
	System.out.println(str == "test"); // --> false 

	
	String str2 = new String("test");
	// ... neither these are same
	System.out.println(str2 == new String("test")); // --> false 

	//but these are because literals are interned by 
	// the compiler and thus refer to the same object
	//Compiler optimizes literals and store same literal in sigle store
	System.out.println("test" == "test"); // --> true 

	// string literals are concatenated by the compiler
	// and the results are interned.
	System.out.println("test" == "te" + "st"); // --> true

	// ... but you should really just call Objects.equals()
	Objects.equals("test", new String("test")); // --> true
	Objects.equals(null, "test"); // --> false
	Objects.equals(null, null); // --> true
}

The first statement in String.equals reads: if (this == anObject) { return true; }, mean == check is already used in equals method. See below how String.equals written

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String) anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                        return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

Best way to compare strings

Suppose you have two string objects.

String s1 = new String("abc");
String s2 = new String("abc");

Then compare them like below

System.out.println(s1.equals(s2)); // It prints true (content comparison)

if you are geeting strings from some other place like return value or in parameter or members of some other object, then compare null first on first object.

if(s1 != null)
{
       System.out.println(s1.equals(s2)); // It prints true (content comparison)
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.