Method equals() is the correct way to compare String objects

Let’s look how method equals() differs from the operator ==:

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

        System.out.println(s1 == s2);       // false
        System.out.println(s1.equals(s2));  // true

        String s3 = "s1";
        String s4 = "s1";

        System.out.println(s3 == s4);        // true
        System.out.println(s3.equals(s4));   // true

Apparently, it compares String objects by the spelling of their values.

But what about object references? Let’s look at the source code of the method:


    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String aString = (String)anObject;
            if (coder() == aString.coder()) {
                return isLatin1() ? StringLatin1.equals(value, aString.value)
                                  : StringUTF16.equals(value, aString.value);
            }
        }
        return false;
    }

As you can see, this method compares references first and compares spelling only if the references are not equal. When equally spelled literals are compared, their references are equal and there is no need to compare their spelling (read this article for the explanation why). So, method equals()  works as fast as possible for all String objects, literals or not.

That is why method equals() does not add any overhead and can be used for comparison of all String objects, whether they were created using operator new or as literals.

Read more detailed discussion of this topic in the following books:

Send your comments using the link Contact or in response to my newsletter.
If you do not receive the newsletter, subscribe via link Subscribe under Contact.

Powered by WordPress. Designed by Woo Themes