5

When we have a reference variable e.g. to simplify it Integer i we can assume that the size of i is approximately 16 bytes overhead + 4 bytes for the actual int + 4 bytes padding i.e. 24 bytes.
So my question is if i is null do we only have 4 bytes of the reference not pointing anywhere or is there any other extra "hidden" information adding to this?

Jim
  • 18,826
  • 34
  • 135
  • 254

2 Answers2

3

If I recall correctly, the JVM specification mentions that null is not required to have a specific value or representation, so it could be anything. What it typically is, I don't know, but a fair guess is probably 32 or 64 bits of zeros, depending on the JVM version.

Edit: Here's the relevant section: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.4

The Java Virtual Machine specification does not mandate a concrete value encoding null.

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
1

Yeah it still uses memory. Uses 4 bytes for a 32bit and 8 for a 64 I believe.

found more information on this: Java - Does null variable require space in memory

Community
  • 1
  • 1
0x2B
  • 91
  • 9
  • 1
    If you set a reference to `null` it does not point to an object on the heap (which consumes heap memory). However the reference itself needs to be stored. As a field in an object or a slot in the local stack frame (if it is a local variable). And this of course occupies as many bytes as the "ordinary object pointer" size is (i.e. 32 or 64bit). In Objects there might be some padding to fields and on stacks there is some reuse (or in case of recursion multiple occurences of the same reference). But thats all independend of the actual value of the reference (null or not). – eckes May 12 '15 at 22:23