Compare String to a literal.. coding style
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/
- Login or register to post comments
- Printer-friendly version
- ahashim's blog
- 1194 reads





