Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...