| |
|
1.13 Scope
The scope of a variable determines for what space it is visible.
- Variables declared at the beginning of a method are visible throughout the method.
- Variables declared globally are visible anywhere in the class.
- When the name of a local variable is the same as a global variable, then local variable is preferred within the method:
public class MyScopeClass {
int i = 7;
public void myMethod() {
int i = 9;
// any code referring to i refers to i=9 } }
|
- Variables declared within a block denoted by curly brackets {} are only visible within that block. This affects loops as well as any other bracketed expression:
... int x = 5; for (int y = 0; y < 10; y++) { // x, y are visible } // only x is visible ...
|
- Even though brackets define a new scope, variables of a given name cannot be re-declared:
... int x = 9; while (true) { int x = 3; // this causes compiler errors } ...
|
|
|