January 28, 2008

Save on string comparisons

I can't claim credit for this, neither can I claim credit for finding it, but I can pass along this tip.

When doing a string comparison, save yourself the NULL check by flipping the left and right side of the comparison.

Instead of writing

if (x != null && x.equals("x")) {
//do something
}

you can write

if ("x".equals(x)) {
//do something
}

You will eliminate the need to check for null.

Posted by doug at 11:49 AM | Comments (0)