AI Hints
Home›Java Tutorial›Overloading, Scope and Pass by Value
Java · Lesson 59 of 120

Scope

Where a variable lives.

⏱ 2 min read▶ Video at 1:13:36🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A variable only exists inside the block where it's created. Outside those curly braces, it's gone. That area is called its scope.

  • Lives in its block
  • Gone outside
  • Called scope

Local and class level

Counter is declared inside the class, but outside any method. Every method in the class can use it, and it keeps its value. Local is declared inside bump. It's created fresh on every call. Doubled only lives inside the loop body. Run it. The counter grows, one, two. But local is always ten.

Main.javajava
public class Main {
    static int counter = 0;

    static void bump() {
        int local = 10;
        counter++;
        System.out.println("local " + local + ", counter " + counter);
    }

    public static void main(String[] args) {
        bump();
        bump();
        for (int i = 0; i < 2; i++) {
            int doubled = i * 2;
            System.out.println("i " + i + ", doubled " + doubled);
        }
    }
}
Output
local 10, counter 1
local 10, counter 2
i 0, doubled 0
i 1, doubled 2

Out of scope

Doubled is created inside the loop. After the loop, we try to print it. Run it. Cannot find symbol. Outside its block, doubled doesn't exist.

Main.javajava
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            int doubled = i * 2;
        }
        System.out.println(doubled);
    }
}
Output
Main.java:6: error: cannot find symbol
        System.out.println(doubled);
                           ^
  symbol:   variable doubled
  location: class Main
1 error
error: compilation failed

Scope rules

A variable lives from where it's declared, to the end of its block. Parameters live inside their method. Loop counters live inside the loop. Keep each variable in the smallest scope you can.

keyvalue
Blockfrom { to }
Parametersinside the method
Loop counterinside the loop
Tipsmallest scope possible

Summary

A variable lives inside the curly braces where it's declared. Outside, it doesn't exist. Next, what really happens when you pass a value to a method.

Key takeaways
  • Block scope
  • Locals are fresh each call
  • Class-level fields last
Next up: Pass by Value — copies, not originals