This question already has an answer here:
-
Which is more effective: if (null == variable) or if (variable == null)? [duplicate]
9 answers
I want to know differences between two conditional expressions null == var
and var == null
in if statement of Java.
There is no difference.Simply a matter of style.
And the first one called as yoda style
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.
Although both conditional expressions null == var
and var == null
are equvilent. But suppose if you introduces bug by misspell ==
(check equality ) as =
(assignment) then var = null
doesn't give you can error and introduce a bug in your code. Whereas you write null == var
and suppose misspells null = var
it produce a compilation time error. And a compilation time error is a way better than a runtime error. That's one of the advantages of the Yoda conditional form.
But I also suggest you read Criticism of Yoda continuations:
Many Programmers hate it, as it has to mentally re-reverse it to understand it. (Others obviously don't have that issue). The practice is referred to as "Yoda conditions". Most compilers can be persuaded to warn about assignments in conditions anyway.
You can also have a look at this:
Which is more effective: if (null == variable) or if (variable == null)?
There are no difference.
for example consider the following piece of code
String x = null;
if(x==null)
{
System.out.println("null");
}
if(null==x)
{
System.out.println("no diff");
}
output
null
no diff
This means that there are no difference
No, there's not. Both statements are true exactly when var
is null
.