Search code examples
javainputstackframe

Input and output, method call and stack frame


I'm currently learning input and output and I'm not sure about this question:

public static int foo(x) {
return 2*x;
}

Suppose the stack contains the following values on entry to foo, from bottom to top, as read left to right:

1 2 3

So 3 is on top and 1 is on the bottom.

Just after foo returns, will the stack be 1 2 6 or 6 2 1? I thought the method would firstly take the value on top and return the value to the top of the stack again.


Solution

  • Most probably, you talk about the stack that the Java Virtual Machine uses internally (as defined in The JVM Specification, Java Virtual Machine Stacks. Quite similar concepts exist in most contemporary programming languages.

    Your assumption is correct, method calling and returning is done at top of the stack. So, 1 2 3 becomes 1 2 6 (that's why it's called a stack, it's hard to manipulate it at some deeply-buried position).