Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Coding Style : What are the cons and pros of "ABC".equals("SOMESTRING") style string comparison? [duplicate]

Tags:

java

string

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..

like image 989
Dreamer Avatar asked Jul 23 '13 13:07

Dreamer


3 Answers

"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.

like image 177
bowmore Avatar answered Oct 06 '22 01:10

bowmore


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 

}
like image 40
Suresh Atta Avatar answered Oct 06 '22 01:10

Suresh Atta


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).

like image 37
TravJenkins Avatar answered Oct 06 '22 01:10

TravJenkins