Java – Memory Difference Between a Variable Assigned to Null and One Not Assigned

java

What is the difference in memory between a variable assigned to null and one not assigned?

I know that there is a difference in usage, but what is the difference in memory?

Best Answer

There is no difference between the two "in memory."

From the Java Language Specification, 4.12.5. Initial Values of Variables :

Every variable in a program must have a value before its value is used:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

...

    • For all reference types (§4.3), the default value is null.

...

    • A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Reference variables at the class or object level will be assigned a null value.

Reference variables at the method (stack) level will have an unspecified value (using the C++ term). In practice this is often null, but the standard does not specify what is in the reference variable, only that it must be assigned before use. Using a reference variable on the stack in any way other than assignment as its first use will result in a compile error.