Java Reference
In-Depth Information
PITFALL: Null Pointer Exception
If the compiler asks you to initialize a class variable, you can always initialize the vari-
able to
null
. However,
null
is not an object, so you cannot invoke a method using a
variable that is initialized to
null
. If you try, you will get an error message that says
“Null Pointer Exception.” For example, the following code would produce a “Null
Pointer Exception” if it were included in a program:
ToyClass2 aVariable =
null
;
String representation = aVariable.toString();
The problem is that you are trying to invoke the method
toString()
using
null
as a
calling object. But
null
is not an object; it is just a placeholder. So
null
has no meth-
ods. Because you are using
null
incorrectly, the error message reads “Null Pointer
Exception.” You get this error message any time a class variable has not been assigned a
(reference to an) object, even if you have not assigned
null
to the variable. Any time
you get a “Null Pointer Exception,” look for an uninitialized class variable.
The way to correct the problem is to use
new
to create a class object, as follows:
ToyClass2 aVariable =
new
ToyClass2("Chiana", 3);
String representation = aVariable.toString();
■
The
new
Operator and Anonymous Objects
Consider an expression such as the following, where
ToyClass
is defined in Display
5.11:
ToyClass variable1 =
new
ToyClass("Joe", 42);
As illustrated in Display 5.13, the portion
new
ToyClass("Joe", 42)
is an invocation
of a constructor. You can think of the constructor as returning a reference to the loca-
tion in memory of the object created by the constructor. If you take this view, the
equal sign in this line of code is just an ordinary assignment operator.
There are times when you create an object using
new
and use the object as an argument
to a method, but then never again use the object. In such cases, you need not give the
object a variable name. You can instead use the expression with the
new
operator and
the constructor directly as the argument. For example, suppose you wanted to test to see
whether the object in
variable1
(in the earlier line of code) is equal to an object with the
same number and with the name spelled in all uppercase letters. You can do so as follows:
if
(variable1.equals(
new
ToyClass("JOE", 42)))
System.out.println("Equal");
else
System.out.println("Not equal");
This is equivalent to the following: