-2

I want to know differences between two conditional expressions null == var and var == null in if statement of Java.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Lyle Wang
  • 69
  • 4
  • 3
    `null==var` called [Yoda condition expression](http://en.wikipedia.org/wiki/Yoda_conditions). `var == null` can be misspelled as `var = null` code will run but if `null==var` will misspelled then it would be compilation time error. Read also [Criticism](http://en.wikipedia.org/wiki/Yoda_conditions#Criticism) – Grijesh Chauhan Sep 23 '13 at 10:05
  • Don't try with equals ;) – Michael Laffargue Sep 23 '13 at 10:06
  • @GrijeshChauhan The most possible reason,You should write that as as anwer. – Suresh Atta Sep 23 '13 at 10:09
  • @sᴜʀᴇsʜᴀᴛᴛᴀ lets add my comment in your answer. usually I rearly answer Java's questions. – Grijesh Chauhan Sep 23 '13 at 10:12

4 Answers4

8

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

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

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
2

You can also have a look at this:

Which is more effective: if (null == variable) or if (variable == null)?

Community
  • 1
  • 1
Sascha M
  • 61
  • 3
0

No, there's not. Both statements are true exactly when var is null.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152