Constant value should always come first in comparison
Written on January 14, 2010 at 2:45 am by
mkyong
Most of the Java developers are using the following way to compare a constant value :
String.equal(CONSTANT_VALUE)
Normal practice
private static final String COMPARE_VALUE = "VALUE123"; public boolean compareIt(String input){ if(input.equals(COMPARE_VALUE)){ return true; }else{ return false; } }
This is fine to compare a constant value with the above method, however it will potentially causing a NullPointerException, if user pass a “null” value for the comparison.
if(input.equals(COMPARE_VALUE)) //hit NullPointerException if input is "null"
Best practice
private static final String COMPARE_VALUE = "VALUE123"; public boolean compareIt(String input){ if(COMPARE_VALUE.equals(input)){ return true; }else{ return false; } }
The best practice should be use the constant value to compare with String, in order to prevent the potential NullPointerException
CONSTANT_VALUE.equal(String)
Oracle Magazine (Free)
Oracle Magazine contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more. Oracle (NASDAQ: ORCL) is the world\'s largest enterprise software company.
Publisher : Oracle Corporation


