- No difference.
- Nope. Java doesn't allocate any space at all for a
null
object, since null
by definition is a reference to no object at all. No object at all takes no space at all. The reference itself will always be 32 or 64 bits long.
- What do you mean by "stored"? A reference variable holds a pointer value, which is always the same size irrespective of the object to which it points. Regardless of the size of the object, even if a reference points to a non-
null
value, the reference size is always the same no matter what type it references. It is the size of the address. I haven't looked, but I'll bet that the null
reference is a special address value such as 0
that points nowhere by definition.
Casting a reference does not change the reference. It still has the exact same value, bit by bit, that it has without the cast.
The only exception to all this is the 32-bit optimization for 64-bit Java. Normally you'd expect all references in 64-bit Java to be, well, 64 bits long. But you can switch on or off the ability to hold references in 32 bits, if certain assumptions about the program hold. But either way, once the JVM decides how wide a reference is, 32 or 64 bits, that will hold true through the program.
So bottom line, no, casting a reference to some other type has no effect on the memory consumed by the reference.
The memory consumed by the object can go to zero if all references to it fall out of scope or become null
.