Where does the JVM store primitive variables?

java, jvm, memory-management

Solution

Simplistic answer: it depends on where the variable is declared, not on its type.

Local variables are stored on the stack. Instance and static variables are stored on the heap.

Don't forget that for reference type variables, the value of a variable is a reference, not the object. (Arrays are reference types too - so if you have an `int[]`, the values will be on the heap.)

Now, this is potentially an overly simplistic answer, because a smart VM may be able to detect if a particular reference type variable refers to an object which can never "escape" the current method. If that's the case, it could potentially inline the whole object on the stack.

But conceptually this model is accurate. So a variable of type `int` which is declared as an instance variable like this:

class Foo
{
    private int value;
    ...
}

will conceptually live on the heap, as part of the data of any instance of `Foo`. It will be freed as part of freeing the instance - it's just 4 bytes within the block of data representing a `Foo` instance; it doesn't need separate deallocation.

Problem

Where does the Java JVM store primitive variables, and how is the memory used by primitives freed after use? I guess it is on the stack?

Original source