This question already has an answer here:
I have a doubt regarding coding standard of a null check. I want to know the difference between
if(a!=null)
and
if(null!=a)
which one is better,which one to use and why?
This question already has an answer here:
I have a doubt regarding coding standard of a null check. I want to know the difference between
if(a!=null)
and
if(null!=a)
which one is better,which one to use and why?
Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and most of them use
null != a
.The
null != a
is an old practice in programming languages like Java,C++ (called as Yoda Conditions).As it is valid to write
if (a = null)
and accidentally assignnull
to thea
so writingnull
first is a guard to stop this accident from happening.No difference betwwen them if statement works based on result of expression so u write either
if(a!=null)
orif(null!=a)
will produce true or false then result is evaluated.So it doesnt matter you write which you like
They're both the same. It depends on your coding style.
They both are same. Although the first variant is common the second variant is useful if you know the first variable is not null
Example
"some value".equals(your_variable)
, some value can be any value you know is not null. This will avoid NPE whenyour_variable
isnull
.Both the conditions will be same if
str
isnull
or not.From the compiler's point of view, they're exactly the same. But the first form is more readable, so I'd advise you to use that one.
There is no difference. But the first is more common. The second is also called "Yoda Conditions" because of its unnatural "grammar".
Once I was working in a project where the coding guideline was to use
if (null != a)
because they thought it is easier for the developer to understand that the constant value has to come first always (as inCONSTANT_VALUE.equals(variable)
. That was pretty annoying to me.