Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Do Java primitives go on the Stack or the Heap?

I just know that the non-primitives (the objects) go on the heap, and methods go on the stack, but what about the primitive variables?

--update

Based on the answers, I could say the heap can have a new stack and heap for a given object? Given that the object will have primitive and reference variables..?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

Primitives defined locally would be on the stack. However if a primitive were defined as part of an instance of an object, that primitive would be on the heap.

public class Test {
    private static class HeapClass {
        public int y; // When an instance of HeapClass is allocated, this will be on the heap.
    }
    public static void main(String[] args) {
        int x=1; // This is on the stack.
    }
}

With regards to the update:

Objects do not have their own stack. In my example, int y would actually be part of each instance of HeapClass. Whenever an instance of HeapClass is allocated (e.g. new Test.HeapClass()), all member variables of HeapClass are added to the heap. Thus, since instances of HeapClass are being allocated on the heap, int y would be on the heap as part of an instance of HeapClass.

However, all primitive variables declared in the body of any method would be on the stack.

As you can see in the above example, int x is on the stack because it is declared in a method body--not as a member of a class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...