Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of "String".equals(otherString)

Tags:

java

string

in a tutorial (for implementing a xml parser) i saw the following code:

if( "NODENAME".equals(xmlreader.getNodeName()) ) {  // getNodeName() returns java.lang.String
... 
}

Is there a reason to write a string comparision like that?.

This may be some kind of best/bad practice or code like that could give some performance benefit. I would like to know if i should use this in commercial projects.

like image 596
some_coder Avatar asked Dec 07 '22 05:12

some_coder


1 Answers

That saves you from a NullPointerException.

That is Yoda Condition used to solve unsafe null behavior.

In programming jargon, Yoda Conditions (also called Yoda Notation) is a programming style where the two parts of an expression are reversed in a conditional statement.

Advantage is

Swapping the two conditional values does not change the behavior of the program. A common mistake is to accidentally assign a value instead of writing a conditional statement.

like image 192
Suresh Atta Avatar answered Dec 21 '22 00:12

Suresh Atta