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

前端 未结 4 1224
时光说笑
时光说笑 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:28

    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.

提交回复
热议问题