Print Page Print Page

CH10 – The null Keyword

  1. Create a new class named SimpleNull.
  2. Create a new main method with the following code. Be certain to import the java.awt.Point class.
import java.awt.Point;
public class SimpleNull {
  public static void main(String[] args){
    Point blank = new Point(120,-99);
    System.out.println(blank);
  }
}
  1. Compile and run the program.
$ javac SimpleNull.java
$ java SimpleNull
java.awt.Point[x=120,y=-99]
  1. Add the following code to the end of main.
blank = null;
System.out.println(blank);
int x = blank.x;
  1. Compile and run the program.
$ javac SimpleNull.java
$ java SimpleNull
java.awt.Point[x=120,y=-99]
null
Exception in thread "main" java.lang.NullPointerException
	at SimpleNull.main(SimpleNull.java:8)

The complete class should appear as follows.

import java.awt.Point;
public class SimpleNull {
  public static void main(String[] args){
    Point blank = new Point(120,-99);
    System.out.println(blank);
    blank = null;
    System.out.println(blank);
    int x = blank.x;
  }
}