Next: Example: scope of local
Up: Unit 03
Previous: Local variables
The scope of a variable is the region of a program in which the
variable is visible, i.e., in which it is accessible by its name and can be
used.
In Java, the scope of a local variable is the body of the method in which it is
declared. In other words, the variable is visible in the body of the method
where its declaration appears, but it is not visible on the outside the method.
Clearly, as we have already said in Unit 2, a variable cannot be used in the
body of a method before it has been declared.
Notes:
- In fact, a more general scope rule holds: the scope of a local variable
extends from the point of its declaration to the end of the block that
encloses it. A block is a statement of the form {...} (see
later). Hence, a local variable is visible in the block in which it is
declared (including sub-blocks, if present), but is not visible outside that
block.
- In Java, the scope of a variable is a completely static notion. Indeed,
it can be determined by analyzing the structure of the program, without
considering its execution. Most current programming languages support such a
notion of static scope.
- If follows that the notion of scope is relevant at compile time.
Next: Example: scope of local
Up: Unit 03
Previous: Local variables