Java Scope
Java Scope
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);
}
}
}
Class Scope
Variables declared inside a class but outside any method have class scope (also called fields). These variables can be accessed by all methods in the class:
Example
public class Main {
int x = 5; // Class variable
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x); // Accessible here
}
}
Note: You will learn more about classes and objects in the Java OOP chapters.