Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
Bart van Heukelom Avatar asked Jun 17 '10 11:06

Bart van Heukelom


1 Answers

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.

like image 57
Joachim Sauer Avatar answered Sep 19 '22 20:09

Joachim Sauer