Reputation: 1182
What is the difference between null!=variable
and variable!=null
Which method is perfect to use?
if ((null != value1) || (null != value2) || (null != value3)) {
.......
.......
.......
}
or
if ((value1 != null) || (value2 != null) || (value3 != null)) {
.......
.......
.......
}
Please suggest the best one and the logical change between these?
Upvotes: 7
Views: 5264
Reputation: 6782
In C assignment looks similar to comparison:
lvalue = rvalue;
lvalue == rvalue;
lvalues (variables) can be assigned to. rvalues can be expressions. Null cannot be assigned to, so if you adhere to use null as the lvalue in comparison, then the compiler will catch the ommision of the second equal sign in a statement like
null = rvalue;
Where you might accidentally assign null with:
lvalue = null;
Upvotes: 2
Reputation: 797
Both the ways of comparision are correct.There is logically no difference but programmers prefer to use value!=null.
Upvotes: 3
Reputation: 8183
null != value
is a hold-over from C. In C, your code will be compiled with no warning in this way:
if (variable = null)
(it's a wrong code), while you actually probably meant if (variable == null)
.
But in Jave both these two styles are OK.
Upvotes: 2
Reputation: 87
As others have mentioned there is not a difference but I haven't ran across something that is
null != value2
I always see it as value2 !=null and like thihara said its easier for readability. I think its also good to keep it the way value != null for beginner programmers who could possibly go over some ones code might get a little lost on the concept even though there is no difference.
Upvotes: 1
Reputation: 6969
Nothing is different.
I prefer value != null
for purely readability reasons.
Upvotes: 4
Reputation: 7870
No difference.
But people quite often write "abc".equals(foo), instead of foo.equals("abc"), to avoid null point exception.
Upvotes: 6