Information Technology Reference
In-Depth Information
Local Variables Inside Nested Blocks
Method bodies can have other blocks nested inside them.
There can be any number of blocks, and they can be sequential or nested further. Blocks
can be nested to any level.
Local variables can be declared inside nested blocks, and like all local variables, their
lifetime is limited to the block in which they are declared.
Figure 5-3 illustrates the lifetimes of two local variables, showing the code and the state of
the stack.
Variable
var1
is declared in the body of the method, before the nested block.
Variable
var2
is declared inside the nested block. It exists from the time it is declared,
until the end of the block in which it was declared.
When control passes out of the nested block, its local variables are popped from
the stack.
Figure 5-3.
The lifetime of a local variable