José María
José María

Reputation: 229

java - What's the difference between (obj != null) and !(obj == null) in an condition?

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

Answers (5)

Andy Turner
Andy Turner

Reputation: 140309

Quoting JLS Sec 15.21.3:

At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.

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 is false, and false if the (possibly converted) operand value is true.

So the two are exactly the same from an evaluation point of view; but != is easier to read.

Upvotes: 3

djm.im
djm.im

Reputation: 3323

No, there is not any difference.
'Not equal to' (!=) is the sam as not be 'Equal to'.

Upvotes: 0

Devendra Lattu
Devendra Lattu

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

fastcodejava
fastcodejava

Reputation: 41087

There is not any difference. (obj != null) is easier to read for most people.

Upvotes: 0

TuyenNTA
TuyenNTA

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

Related Questions