Eric Jiang
Eric Jiang

Reputation: 597

Why do DUP when creating new instance

Currently I'm just in a project which uses java bytecode. I usually see that when creating a new class instance and invoke a method on it, the bytecode will be like:

NEW <MyClass>
DUP
INVOKESPECIAL <MyClass.<init>>

Here why should do "DUP"? From VM Spec, I get the description "Duplicate the top value on the operand stack and push the duplicated value onto the operand stack". But why duplicating the top value on the operand stack is necessary here? Thanks.

Upvotes: 13

Views: 1325

Answers (1)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

Because INVOKESPECIAL will consume value created by NEW from the operand stack, but you may need to actually use this value, so the reference is duplicated in advance.

Upvotes: 20

Related Questions