tags:

views:

284

answers:

3

Was this an oversight? Or is it to do with the JVM?

+2  A: 

I guess it has to do with the fact that the JVM is coded in C++. Apart from that, pointers and references are nearly similar. You could say that the reference mechanism in Java is implemented using C++ pointers and the name 'NullPointerException' allows that implementation detail to shine through.

Confusion
+1  A: 

This is due to the fact that Java was designed with C programmers in mind. In C terminoligy the word 'pointer' is used instead of 'reference'

Martin OConnor
yeah but Java uses reference :p
hhafez
+8  A: 

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 and reference types. 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 and reference values.

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.

David Citron