Can null
be
assigned to reference variables of any type?
Yes.
It would be awful if each class had its own special value
to show that no object of that class was present.
We need a universal value that means "nothing here".
The value null
works for this and can be assigned to any reference variable.
In most programs, objects come and objects go, depending on the data and on what is being computed. (Think of a computer game, where monsters show up, and monsters get killed). A reference variable sometimes does and sometimes does not refer to an object, and can refer to different objects at different times. You need a way to say that a variable does not now refer to an object. You do this by assigning null to the variable.
Inspect the code below.
Variables a
and c
are
initialized to object references.
Variable b
is initialized to null.
class NullDemo1 { public static void main (String[] arg) { String a = "Random Jottings"; String b = null; String c = ""; if ( a != null ) System.out.println( a ); if ( b != null ) System.out.println( b ); if ( c != null ) System.out.println( c ); } }