In Java, variables are only accessible inside the region where they are created. This is called scope .
Method Scope
Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:
Example
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x int x = 100; // Code here CAN use x System.out.println(x);
}
}Block Scope
A block of code refers to all of the code between curly braces { } .
Variables declared inside a block of code are only accessible by the code between the curly braces, and only after the line in which the variable was declared:
Example
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x { // This is a block // Code here CANNOT use x int x = 100; // Code here CAN use x System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}A block of code can stand alone, or be part of an if , while , or for statement. In a for loop, the variable declared in the loop header (like int i = 0 ) only exists inside the loop.
Loop Scope
Variables declared inside a for loop only exist inside the loop:
Example
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i); // i is accessible here
}
// i is NOT accessible here
}
}- The for loop has its own block ( { ... } ).
- The variable i declared in the loop header ( int i = 0 ) is only accessible inside that loop block.
- Once the loop ends, i is destroyed, so you can't use it outside.
Why this matters
Loop variables are not available outside the loop.
You can safely reuse the same variable name ( i , j , etc.) in different loops in the same method:
Example
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println("Loop 1: " + i);
}
for (int i = 0; i < 2; i++) {
System.out.println("Loop 2: " + i);
}
}
}