22 February 2011

Java: Please make best use of String.equals and equalsIgnoreCase

Al salamo Alykom,

May developers don't make the best use of java.lang.String.equals and java.lang.String.equalsIgnoreCase

Take this example:
public static CreditCart getCreditCard(String creditCardId)
{
    if (creditCardId != null && creditCardId.equalsIgnoreCase("vi"))
        return new Visa();
    else if (creditCardId != null && creditCardId.equalsIgnoreCase("mc"))
        return new MasterCard();
    else
        return new NullCard();
}

But the best use of equals and equalsIgnoreCase will make your code much compact, watch out:

public static CreditCart getCreditCard(String creditCardId)
{
    if ("vi".equalsIgnoreCase(creditCardId))
        return new Visa();
    else if ("mc".equalsIgnoreCase(creditCardId))
        return new MasterCard();
    else
        return new NullCard();
}

this is because, equalsIgnoreCase and equals returns (from Javadoc):
true if the argument is not null and it represents an equivalent String ignoring case; false otherwise

So, if the argument (in our case `creditCardId` is null, no NullPointerException will be thrown, but simple the expression will be evaluated to false!)

1 comment:

mohammed fathei said...

good bro hewedy

thanks