Difference between null! = Variable and variable! = Null
What is the difference between null!=variable
and variable!=null
Which method is ideal to use?
if ((null != value1) || (null != value2) || (null != value3)) {
.......
.......
.......
}
or
if ((value1 != null) || (value2 != null) || (value3 != null)) {
.......
.......
.......
}
Please suggest a better and logical change between them?
No difference.
But people quite often write "abc" .equals (foo) instead of foo.equals ("abc") to get rid of the null dot exception.
Nothing changed.
I prefer it value != null
for pure readability.
Both methods of comparison are correct. There is no logical difference, but programmers prefer to use the value! = Null.
As mentioned, there is no difference, but I have not come across something that is
null != value2
I always see it as value2! = Null and as thihara said it is easier to read. I think it's also okay to keep this value! = Null for beginner programmers who might have walked through some of these might get a little lost in concept, although there is no difference.
null != value
is a holdover from C. In C, your code will be compiled without warning in this way:
if (variable = null)
(this is wrong code) while you probably meant if (variable == null)
.
But in Jave, both of these styles are fine.
In assignment C looks like a comparison:
lvalue = rvalue;
lvalue == rvalue;
lvalues (variables) can be assigned. rvalues can be expressions. Null cannot be assigned, so if you stick with using null as the lvalue in the comparison, then the compiler will catch the ommision of the second equal sign in an expression like
null = rvalue;
If you can accidentally assign null, do the following:
lvalue = null;