views:

121

answers:

4

Are both the String comparison methods below considered to be equal

public class TestString {
    public static final String CONSTVAL="foo";

    public boolean testString1(String testVal) {
        return testVal.equalsIgnoreCase(CONSTVAL);
    }

    public boolean testString2(String testVal) {
        return CONSTVAL.equalsIgnoreCase(testVal);
    }
}

or should one type of comparison be favoured over another?

+5  A: 

One advantage of the latter is that it won't throw an exception if testVal is null.

I would expect the results to be the same, other than that.

Jon Skeet
+16  A: 

You should call equals on the constant since it avoids the risk of NullPointerException when testVal is null.

public boolean testString2(String testVal) {
    return CONSTVAL.equalsIgnoreCase(testVal);
}
Jcs
A: 

When a constant value compare itself to another value you're almost sure to not have null value.

In your case,

new TestString().testString1(null);

will throw an exception, whereas,

new TestString().testString2(null);

wont.

But this kind of notation could be considered as a yoda condition.

Colin Hebert
+2  A: 

At first glance I would agree with @Jon Skeet, but then I noticed that CONSTVAL isn't final.

If it was final then testString2() is the safest and best way to test for equality.

Eran Harel
My mistake, I should have added final to the const val
Pram
@Eran: i too missed that :)
Rakesh Juyal