03 October 2008

better way of comparing Strings

Lets say there is some String variable, to be compared with some static value in the program,
what generally developers do is to explicitly check on 'nulls' and use equalsIgnoreCase() to compare with that static String.
For example, consider varString is of type String and is to be compared with the static value "Success". Generally to check whether the varString is 'Success' or not, I see people coding it like
if(varString != null && varString.equalsIgnoreCase("Success")) ...
but there is another better way of doing this, that is simply write
if("Success".equalsIgnoreCase(varString)) ...
the above statement includes the check on nulls and the String value at once. No one claims there could be performance uplift due to this statement, but code looks credible and simple.
Just try....

No comments:

Post a Comment