Web Analytics

Variable Scope

Beginner ~10 min read

In Java, variables are only accessible inside the region 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 declaration.

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 is code between curly braces {}. Variables declared inside blocks (like if statements or for loops) are only accessible inside that block.

Java Scope Visibility Diagram
Common Error: Trying to access a variable declared inside an if block from outside of it.
if (condition) {
    int y = 50; // 'y' is created here
    System.out.println(y);
}
// 'y' is destroyed here
// System.out.println(y); // ERROR!
Output
Click Run to execute your code

Loop Scope

Variables defined in the loop header (like int i in a for-loop) only identify inside the loop.

for (int i = 0; i < 5; i++) {
    // 'i' works here
}
// 'i' DOES NOT exist here

Summary

  • Scope determines where variables can be accessed.
  • Method Scope: Variables accessible throughout the method.
  • Block Scope: Variables accessible only within the {} they are defined in.