A variable is a named region in memory that is used for storing a value.
What is variable and value?
A variable is just an association between the name and the slot of memory. A variable has a value, that is the content of the memory slots associated with it. The size of the slot and the value of the variable depends upon the type of variable.
Where are the things stored?
The memory slots of the variable are stored on the stack or heap. So it depends upon the context in which it is declared.
- Each local variable is stored on the stack. That includes the reference type variable which is the variable on the stack so one thing has to remember that the value of the reference type variable is only a reference, not the object itself.
- Instance variables for a reference type are always stored on the heap. That is where the object itself is live.
- Instance variables for a value type are stored in the same context as the variable that declares the value type. The memory slot for each field contains the field within the instance.
- Every static variable is stored on the heap regardless of whether it is declared within the reference type or a value type.