I'm told this is because the JVM does not allocate space in memory until an object is initialized.
If you have an instance array variable (auto initialized with a default value of null), does that variable point to a place in the heap indicating null?

4 Answers
4

No, because in the JVM there's no need for that.
If you're in a native language (C and C++, for instance), NULL is a pointer with a zero value, and that points to the memory base address. Obviously that's not a valid address, but you "can" dereference it anyway - especially in a system without protected memory, like old MS-DOS or small ones for embedded processors. Not that it would be a valid address - usually that location contains interrupt vectors and you shouldn't touch them. And of course in any modern OS that will raise a protection fault.

But in the JVM a reference to an object is more like a handle (i.e. an index in a table) and null is an 'impossible' value (an index that is outside the domain of the table), so it can't be dereferenced and doesn't occupy space in such table.

"Obviously that's not a valid address" - this is just incorrect. 0 is a perfectly valid memory address. There are many computing platforms where address 0 is valid. It's entirely up to the hardware and software (OS) as to whether 0 is valid.
–
Steve KuoNov 15 '11 at 0:19

I understand, but I was talking in the context of the question asked, in which we are dealing with pointers to objects (class instances). A C++ class instance can't reside at 0, because the whole purpose of the null pointer is to be an "impossible" value for a valid pointer and thus signal it as invalid/empty/uninitialized/etc.
–
Fabio CeconelloNov 15 '11 at 23:11

In Java, null is just a value that a reference (which is basically a
restricted pointer) can have. It means that the reference refers to
nothing. In this case you still consume the space for the reference.
This is 4 bytes on 32-bit systems or 8 bytes on 64-bit systems.
However, you're not consuming any space for the class that the
reference points to until you actually allocate an instance of that
class to point the reference at.

Edit: As far as the String, a String in Java takes 16 bits (2 bytes)
for each character, plus a small amount of book-keeping overhead,
which is probably undocumented and implementation specific.

A null reference is literally a zero-value. The operating system prevents any program from accessing the zero address in memory, so the JVM will proactively check and make sure that a reference value isn't zero before allowing you to access it. This lets the JVM give you a nice NullPointerException rather than a "The program has performed an Illegal Operation" crash.

So you could say that the variable "points to" an invalid heap location. Or you could just say the variable doesn't "point to" anything. At that point it's just a question of semantics.