Was this an oversight? Or is it to do with the JVM?
Advertisement
Answer
Java does indeed have pointers–pointers on which you cannot perform pointer arithmetic.
From the venerable JLS:
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
And later:
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
(emphasis theirs)
So, to interpret, if you write:
Object myObj = new Object();
then myObj
is a reference type which contains a reference value that is itself a pointer to the newly-created Object
.
Thus if you set myObj
to null
you are setting the reference value (aka pointer) to null
. Hence a NullPointerException is reasonably thrown when the variable is dereferenced.
Don’t worry: this topic has been heartily debated before.