Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison order in Java

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?

like image 512
Pram Avatar asked Sep 04 '10 08:09

Pram


2 Answers

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);
}
like image 163
Jcs Avatar answered Sep 18 '22 15:09

Jcs


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.

like image 27
Jon Skeet Avatar answered Sep 16 '22 15:09

Jon Skeet