Recall: Variable Scope
• The scope of a variable is the portion of a program
in which the variable can be used.
• By default, the scope of a variable in Java:
• begins at the point at which it is declared
• ends at the end of the innermost block
that encloses the declaration
public class MyProgram2 {
public static void main(String[] args) {
System.out.println("Welcome!");
System.out.println("Let's do some math!");
int j = 10;
System.out.println(j / 5);
}
}
scope of j
Special Case: for Loops and Variable Scope
• When a variable is declared in the initialization clause of
a
for loop, its scope is limited to the loop.
•Example:
public static void myMethod() {
for (int i = 0; i < 5; i++) {
int j = i * 3;
System.out.println(j);
}
// the following line won't compile
System.out.print(i);
System.out.println(" values were printed.");
}
scope of i