Java Reference
In-Depth Information
As the comments indicate, the variable x is declared at the start of main( ) 's scope and is
accessible to all subsequent code within main( ) . Within the if block, y is declared. Since a
block defines a scope, y is visible only to other code within its block. This is why outside
of its block, the line y = 100; is commented out. If you remove the leading comment sym-
bol, a compile-time error will occur, because y is not visible outside of its block. Within the
if block, x can be used because code within a block (that is, a nested scope) has access to
variables declared by an enclosing scope.
Within a block, variables can be declared at any point, but are valid only after they are
declared. Thus, if you define a variable at the start of a method, it is available to all of the
code within that method. Conversely, if you declare a variable at the end of a block, it is
effectively useless, because no code will have access to it.
Here is another important point to remember: variables are created when their scope is
entered, and destroyed when their scope is left. This means that a variable will not hold its
value once it has gone out of scope. Therefore, variables declared within a method will not
hold their values between calls to that method. Also, a variable declared within a block will
lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, that variable will be reinitialized each
time the block in which it is declared is entered. For example, consider this program:
Search WWH ::




Custom Search