in a tutorial (for implementing a xml parser) i saw the following code:
if( \"NODENAME\".equals(xmlreader.getNodeName()) ) { // getNodeName() returns java.l
The method equals()
checks for the contents of the String
.
calling the equals()
method on literal saves you from NullPointerException
which may happen if xmlReader.getNodeName()
returns null
. Calling equals
method on null
will cause NullPointerException
If you have code:
if( "NODENAME".equals(xmlreader.getNodeName()) ){...}
It will avoid NullPointerException
when xmlreader.getNodeName()
is null
since
"NODENAME".equals(null)
will return false instead of NullPointerException
.
PS: Keep in mind that if for some reason xmlreader
itself is null then:
"NODENAME".equals(xmlreader.getNodeName())
can still throw NullPointerException
.
Usually string comparison was written like that to avoid NullPointerException
if xmlreader.getNodeName()
is null, because then you would have
if("NODENAME".equals(null)) {
// ...
}
compared to
if(null.equals("NODENAME")) {
// ...
}
which would've thrown.
This is called Yoda condition:
if you expect xmlreader.getNodeName()
to be null
then it's ok, otherwise I would not rely on this to avoid the exception to be thrown, you should rather deal with it earlier on in your code.
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.
Since equals is a built in method in java , we need to make sure that it should be called with object not with null. so in case if we call with null then we will endup with Null pointer exception.
Ex : assume i need to check whether string a is equal to "hai" and a is coming from user.
then i am not sure whether 'a' will be null or not. so if i use a.equals("hai")
then its not safe if a becomes null but if you reverse the comparison then it is always safe no matter a is null or not.
so always prefer "hai".equals(a)
to be safe from null pointer exception.
Its called a Yoda condition and used to avoid NullPointerException
. Regarding its use in commercial projects, this is really a design decision - some developers want to be protected against null values whereas others want the fail fast mechanism offered by the conventional notation.