TanP
TanP

Reputation: 77

Where does the constructor invocation get stored? Stack or Heap?

When an object is created and the constructor is called where does the constructor invocation get stored? is it on a stack or heap?

Upvotes: 4

Views: 2100

Answers (3)

Shweta Gulati
Shweta Gulati

Reputation: 606

Heap is only meant for storing objects . There is no way to have constructor invoked on heap.

It's invocation is done on stack.

Stack is used in method calling. It is used for creating method stacks. Although constructor is not a method. But you can always write any logic or assignment as is always done In any method. So it's implemented in a stack like any other method.

Upvotes: 1

Stephen C
Stephen C

Reputation: 718798

The parameters and local variables for the constructor call are stored on the stack until the constructor returns.

The object that the constructor creates is stored in the heap1.


1 - ... unless you have "escape analysis" enabled, and the JIT compiler can determine that the object can be safely allocated on the stack.

Upvotes: 4

Ajay Pal
Ajay Pal

Reputation: 563

Runtime data area in JVM for stack and heap is as below,

1) Heap : Storage area for Objects.(One per JVM instance)

2) Java stack: Storage are for local variables, results of intermediate operations.(One per thread)

Upvotes: 1

Related Questions