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?
There are two kinds of memory used in Java. These are called stack memory and heap memory. Stack memory stores primitive types and the addresses of objects. The object values are stored in heap memory.
➲ In Java, all data type for primitive type variables is stored on the stack. ➲ For reference data types, the stack holds a pointer to the object on the heap.
Primitive Data Types. The eight primitives defined in Java are int, byte, short, long, float, double, boolean and char. These aren't considered objects and represent raw values. They're stored directly on the stack (check out this article for more information about memory management in Java).
As discussed, the reference types in Java are stored in heap area. Since arrays are reference types (we can create them using the new keyword) these are also stored in heap area.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With