Reputation: 229
I have the following question, for Java programmers.
Does there be any difference between setting (obj != null)
rather than !(obj == null)
?
Upvotes: 0
Views: 289
Reputation: 140309
Quoting JLS Sec 15.21.3:
At run time, the result of
==
istrue
if the operand values are bothnull
or both refer to the same object or array; otherwise, the result isfalse
.The result of
!=
isfalse
if the operand values are bothnull
or both refer to the same object or array; otherwise, the result istrue
.
And JLS Sec 15.15.6, which describes the logical complement operator (!
):
At run time, the operand is subject to unboxing conversion (§5.1.8) if necessary. The value of the unary logical complement expression is
true
if the (possibly converted) operand value isfalse
, andfalse
if the (possibly converted) operand value istrue
.
So the two are exactly the same from an evaluation point of view; but !=
is easier to read.
Upvotes: 3
Reputation: 3323
No, there is not any difference.
'Not equal to' (!=
) is the sam as not be 'Equal to'.
Upvotes: 0
Reputation: 2802
NO difference.
Also, some prefer having null
close to each other while making a conditional check.
if(obj1 == null || null == obj2) // looks better to read
...
if(obj1 == null && obj.method()) // have high chances to throw an exception
even if True && this will be checked
if(obj1 == null || obj.method()) // is preferred over the above one
if True || this will be NOT be checked
Upvotes: 0
Reputation: 41087
There is not any difference. (obj != null)
is easier to read for most people.
Upvotes: 0
Reputation: 1204
There are no difference here, the !(obj==null) is just the another way for writing (reverse), and it also hard to understand than the first one.
Upvotes: 0