Search code examples
javascopestackjavacjls

Are subcontexts in Java separate rows on the stack?


In Java this is the case:

public void method() {
  if (condition) {
    Object x = ....;
  }
  System.out.println(x); // Error: x unavailable
}

What I'm wondering is this: Is the fact that x is limited to the scope of the if-statement just a feature of the Java compiler, or is x actually removed from the stack after the if-statement?


Solution

  • No, code blocks don't get a separate stack frame, the use the one of the surrounding method.

    However, once a variable leaves scope, it's place in the current stack frame can be re-used for other variables.

    The structure and use of a stack frame is described in the Java Virtual Machine Specification § 3.6 Frames:

    A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt (it throws an uncaught exception).

    This definitely specifies a 1:1 relation between method invocations and frames.