Let me first start-of with a sample code...
String password = "";
if("PIRATE".equals(password)) {
// Do something
}
See here, the String constant or literal (whatever) "PIRATE" is used to check the equality of the two Strings. Whereas...
String password = "";
if(password.equals("PIRATE")) {
// Do something
}
this also works exactly as the previous code.
Now-a-days, I see a lot of the first style "STRING_LITERAL".equals(STRING_OBJECT), while Java people post code.
So my question is, Where does this style comes from ? and Is it better than the second style in any way ?
In-fact i find the second style more logical than the first one, why ?!
lets take a requirement like, if the user-provided-password is equal to the "PIRATE" then give permission to that user
when you start implementing the above requirement,
String userProvidedPassword = getPaswordFromUser();
if(userProvidedPassword.equals("PIRATE")) {
// Allow him
}
Doesn't this more logical than "PIRATE".equals(userProvidedPassword); ?! Just think about it...
Correct me if I'm wrong.. Thanks..
EDIT : Sorry, this question didn't come up in my previous search, and it answers my question perfectly. Also thanks to all those who helped out here..
"PIRATE".equals(password)
cannot result in a NullPointerException
.
whereas
password.equals("PIRATE")
will throw a NullPointerException
if password
happens to be null
.
Therefore the use of the former is encouraged : it is safer.
When you write password.equals("PIRATE")
you are almost asking for a NullPointerException
,where there are chances for password
might null.
It's all about Avoiding NullPointerException
.
if("PIRATE".equals(password)) {
// Do something
}
Avoids NullPointerException
where as
if(password.equals("PIRATE")) {
// Do something
}
thrwos you NullPointerException
if password
is null
.
However ,Personally I feel this is looks odd in middle of the code. and I always prefer to write
if(password !=null && password.equals("PIRATE") ){
//do something
}
The only con is really a style problem. Saying "PIRATE".equals(password) is called a Yoda Condition. However, as people have already stated, it is safer to use that kind of condition (so I would keep using that kind).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With