The Source for Java Technology Collaboration
User: Password:



Ahmed Hashim's Blog

J2SE Archives


Compare String to a literal.. coding style

Posted by ahashim on March 10, 2007 at 04:11 AM | Permalink | Comments (7)

I saw many times code written by geeks, comparing String to literals in this style

public boolean compareUser(String name)
{
if("Ahmed Hashim".equals(name))
{
//do staff here
return true;
}
return false;
}
what is the difference between this and the normal code style?
public boolean compareUser(String name)
{
if(name.equals("Ahmed Hashim"))
{
//do staff here
return true;
}
return false;
}
You will miss the difference if you call both versions of the function like this


compareUser(null);

I think you got it, passing null will not need check in the first version because you are not accessing the “.equals” method inside the passed object, while the 2nd version will cause NullPointerException!

Mirror:
http://egjug.org/hashimblog/2007/03/08/compare-string-to-a-literal-coding-style/





Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds