Java ยท Chapter 20 of 42

Java Scope

Scope determines where a variable can be accessed in your code. Local variables declared inside a method exist only within that method, while instance variables belong to an object and exist as long as the object does.

Variables declared inside a block (like a for loop or if statement) are only visible within that block.

Syntax
class C {
  int instanceVar; // instance scope
  void m() {
    int localVar; // local scope
  }
}

Local vs instance scope

Local variables live inside methods and are destroyed when the method returns. Instance variables belong to an object and live as long as the object does.

Block scope

Variables declared inside {} braces, such as inside a loop, are only accessible within that block.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 2; i++) {
      int local = i * 10;
      System.out.println(local);
    }
  }
}
Output
0
10

local and i are only accessible inside the for loop block.

Key points

  • Local variables exist only inside their method or block.
  • Instance variables exist as long as the object exists.
  • Block-scoped variables cannot be accessed outside their braces.
  • Scope helps avoid naming conflicts.
๐Ÿ’ก Note: Accessing a variable outside its scope causes a compile-time error.

๐Ÿ“ Quick Quiz

1. Where do local variables live?

2. How long does an instance variable live?

3. Can a variable declared inside a for loop be used after the loop?