In Java null is the initial value of every uninitialized reference variable:
SpaceShip falcon; // falcon = null
Note that this implies that the null reference can masquerade as a reference to any type of object, including an array.
We should test for null before we invoke any methods:
if (falcon != null) {
falcon.fireLasers();
}
Often null is returned as an indication that a search has failed:
SpaceShip find(String name) {
for(SpaceShip s: fleet) {
if (name.equals(s.getName())) {
return s;
}
}
return null; // spaceship not found ;-(
}
In C null is simply taken as 0, but this isn't true in Java. The JVM threats null as a special constant named aconst_null.
For example:
aconst_null ; ldc null
aload 1 ; load falcon
if_acmpeq ERROR ;
note use of if_acmpeq (or if_acmpne) to compare addresses
; fire lasers
goto DONE
ERROR:
; print error message
DONE:
Another example:
.method public find(Ljava/lang/String;)LSpaceship;
; search for name and return if found,
else:
aconst_null ; ldc null
areturn
.end method