ReferenceToBooleanCoercionDRAFT
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
CorrectionHere 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
OriginWhere could this misconception come from?
Students may incorrectly transfer their understanding
of Python or JavaScript,
where conditional statements to test for nullness of reference variables
(like if o:
in Python or if (o)
in JavaScript)
are common.
SymptomsHow do you know your students might have this misconception?
This misconception may surface especially in the context of conditionals.
In the following code, the condition in the if
-statement
seems to be used as a null check.
Students may incorrectly believe that this code compiles.
void m(Ghost g) {
if (g) {
g.work();
}
}