Filip
Filip

Reputation: 2344

Java check for null practise

Usual practice I have seen so far is to check like this:

if (object != null) {...}

But today I have encountered the following situation:

if (object) {...}

Are these two lines COMPLETELY equivalent? The latter seems little bit strange to me, since the object is not neccesary a Boolean. Is it better(shorter) to write in latter way?

Upvotes: 1

Views: 58

Answers (2)

Mena
Mena

Reputation: 48404

Absolutely not.

The if (object) syntax will only work if object is an instance of primitive boolean, and by proxy, wrapper class Boolean (auto-unboxed).

Also note that the if (object) syntax will work with weaker typed languages such as Groovy or JavaScript, with all caveats implied.

Finally note that a Boolean wrapper is also nullable in Java, hence the if (object != null) syntax would actually make sense too for Booleans (but wouldn't compile for primitive booleans).

Upvotes: 3

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

The code

if (object) {...}

is not java syntax, but javascript.

In java that code works only if object is of type Boolean and is not null.

Upvotes: 2

Related Questions