Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the JVM store primitive variables?

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?

like image 674
JRomio Avatar asked Sep 13 '10 05:09

JRomio


People also ask

Where are primitives stored in JVM?

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.

Where are primitive type variables stored in Java?

➲ 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.

How does Java store primitive types?

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).

Where will JVM store the values?

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.


1 Answers

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.

like image 153
Jon Skeet Avatar answered Sep 25 '22 05:09

Jon Skeet