An expression of a reference type can be coerced to boolean. The value null becomes false, every other value becomes true. This allows conditions like String s = get(); if (s) ....


Every reference type can be coerced to boolean


Not every reference type can be coerced to boolean

Here is what's right.

Java separates reference types and boolean types. There is no implicit coercion from arbitrary reference types to boolean.

Pacman pac = ...;

boolean b = pac; // compiler error

As Section 4.2.5 of the Java Language Specification describes, to convert an arbitrary reference to a boolean, one can use comparison operators:

if (i != null) {

Exception: Auto-Unboxing

The one exception is the auto-unboxing of a reference to a Boolean object to boolean:

boolean b;

b = new Boolean(true);                  // b == true
b = new Boolean(false);                 // b == false

This even works for expressions of type Object, which is a supertype of Boolean:

boolean b;

Object o = new Boolean(true);
b = (boolean)o;               // b == true

However, when auto-unboxing null will not be converted to false, but instead the unboxing will cause a NullPointerException:

boolean b;

b = (Boolean)null;         // throws NullPointerException
b = (boolean)null;         // compiler error
b = (boolean)(Object)null; // throws NullPointerException

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.