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?
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 Boolean
s (but wouldn't compile for primitive boolean
s).
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.