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

前端 未结 4 1233
时光说笑
时光说笑 2020-12-01 09:50

I have a question

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

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

Where

4条回答
  •  孤街浪徒
    2020-12-01 10:35

    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.

提交回复
热议问题