Where is allocated variable reference, in stack or in the heap?

I have a question

What happend when I declare a variable inside a method, for example.

void myMethod() {
    Ship myShip = new Ship();
}

Where is allocated myShip reference, in stack or in the heap ?

I think in stack but I'm confused because I was reading in J2ME Game Programming book "Java classes are instantiated onto the Java heap"

All java clases ?

Thanks in advance


myShip is a reference to a Ship object, myShip is on the method call stack, which is referred to as "the stack". When a method is called a block of memory is pushed onto the top the stack, that memory block has space for all primitives (int, float, boolean etc) and object references of the method, which includes the method parameters. The heap is where the memory for the actual objects is allocated.

So myShip is on the stack and the Ship object is on the heap.

Note each thread has its own stack but share the heap.


Java really does things a bit differently. The reference is basically on the stack. The memory for the object is allocated in what passes for the heap. However, the implementation of allocable memory isn't quite like the way the heap is implemented in the C/C++ model.

When you create a new object like that, it effectively puts the name into the table of references for that scope. That's much like a pointer to an object in C++. When it goes out of scope, that reference is lost; the allocated memory is no longer referenced, and can be garbage-collected.


Currently, all Java objects are allocated on the heap. There is talk that Java 7 might do escape analysis and be able to allocate on the stack, but I don't know if the proposal is finalized yet. Here's the RFE.

Edit: Apparently, it's already in early builds of JDK 7. (The article says it will also be in JDK 6u14, but I can't find confirmation.)

链接地址: http://www.djcxy.com/p/82818.html

上一篇: “静态分配”堆栈中的变量?

下一篇: 哪里分配了变量引用,堆栈还是堆?