null assignment Example
The null keyword is used to signify a reference to nothing, or an absence of reference.null can be assigned to a variable of any reference type.
It is sometimes used to initialize a variable that may or may not subsequently be assigned some other value. It can then be convenient to test the variable for a null value in order to determine future processing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Null Assignment Example
class NullAssignmentStatementExample {
public static void main(String[] args) {
ABox b0 = new ABox();
b0.draw();
ABox b1 = null;
//b1.draw();
}
}
6-7 b0 is initialized and will point to a box object. This means that b0 can be used as a reference for methods such as draw().
9 b1 is assigned a null value.
Notice that the following statement has been commented out. If it had not, then a run error would have occurred.
This is because a null reference does not reference an object, and an object is required for the method draw() to execute.
