Is there any difference between (null == var) and

2019-06-14 19:13发布

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

4条回答
贪生不怕死
3楼-- · 2019-06-14 19:42

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.

查看更多
三岁会撩人
4楼-- · 2019-06-14 19:46

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

查看更多
Rolldiameter
5楼-- · 2019-06-14 19:57

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

查看更多
登录 后发表回答