Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 201 ยท Methods

Variable Scope

Understand Java variable scope - block and method scope, loop variables, fields vs local variables, shadowing with this, pattern variable scope and how long variables live.

Every variable in Java has a scope: the region of source code where its name can be used. Outside that region, the name simply doesn't exist, and using it is a compile error. Scope is why you can call a loop counter i in ten different loops, why two methods can both have a variable called total without interfering, and why a value computed inside an if block can vanish before you get to print it.

Closely related is a variable's lifetime: how long its value exists while the program runs. A local variable lives only while its block is running; a field lives as long as its object (or, for static fields, as long as the class is loaded). This lesson covers block and method scope, fields versus local variables, shadowing, the scope of pattern variables, and the habits that keep scope working for you instead of against you.

Block scope

A block is any group of statements in braces { }: a method body, the body of an if, a loop, a try, or even a bare pair of braces. A local variable is in scope from the point where it's declared to the end of the block that contains it:

Java
void main() {
    int a = 1;                 // a: from here to the end of main
    if (a > 0) {
        int b = 2;             // b: only inside this if block
        IO.println(a + b);     // fine: a and b are both in scope
    }
    IO.println(b);             // error: cannot find symbol: b
}

Two details matter:

  • Scope starts at the declaration, not the top of the block. Using a variable on a line above its declaration is an error, even within the same block.
  • Inner blocks see outer variables, not the other way around. The if body can read and change a. Code after the if can't see b.

The most common scope bug follows directly from this: computing a value inside a block and needing it afterward.

Java Declare before the block when you need the value after it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler also checks that ticket is definitely assigned on every path before it's read (Variables introduced this rule). If you removed the else branch, IO.println(ticket) would fail with variable ticket might not have been initialized.

Loop variables

A variable declared in a for header belongs to the loop. It's in scope in the header and body, and gone afterward. Variables declared inside a loop body are created fresh on each iteration:

Java Loop scope and per-iteration variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both loops use i without conflict, because the first i went out of scope when its loop ended. When you need the value of the counter or a result after the loop (like the index where a search stopped), declare that variable before the loop.

Other scopes you'll meet

  • Method parameters are in scope for the whole method body.
  • catch parameters, like e in catch (IOException e), exist only in that catch block.
  • Resources declared in try (var in = ...) exist in the try block (try-with-resources).
  • switch cases. In a classic switch with colons, the whole switch body is one block, so a variable declared in one case is visible (but not initialized) in later cases. Arrow cases (case X -> { ... }) each get their own block, which is one more reason to prefer them (switch).

No redeclaring in nested scopes

Some languages let an inner block declare a variable with the same name as an outer local, hiding it. Java forbids this for local variables and parameters, which prevents a whole category of bugs:

Java
void process(int count) {
    int total = 0;
    for (int i = 0; i < count; i++) {
        int total = i * 2;     // error: variable total is already defined in method process(int)
        int count = 5;         // error: variable count is already defined in method process(int)
    }
}

Sibling blocks are fine, because their scopes don't overlap. Two separate if blocks may each declare their own temp, and two loops may each declare i.

Fields vs local variables

Variables declared inside a method are local variables. Variables declared directly in a class, outside any method, are fields. Their scope is the entire class: every method can use them, regardless of where in the class they're declared.

Local variable Field
Declared inside a method or block in the class body, outside methods
Scope from declaration to end of block the whole class (and beyond, depending on access modifiers)
Lifetime while the block runs as long as the object exists (static: as long as the class)
Default value none: must be assigned before use 0, false or null
Shared between method calls no: each call gets fresh locals yes: values persist

In a compact source file, a variable declared at the top level, next to your methods, is a field of the hidden class. That makes the difference easy to see:

Java A field remembers; a local starts over

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each call to recordVisit gets a brand-new visitsThisCall starting at 0, which disappears when the method returns. totalVisits lives outside any call, so it accumulates. Notice also that the field didn't need an initializer to be usable: fields get default values, while locals must be assigned first.

In a classic public class Main with static methods, the equivalent field is static int totalVisits = 0;, because static methods can only use static fields directly. You'll learn the full story of instance and static fields in Fields and Instance Methods and Static Fields, Methods and Blocks.

Fields are convenient, which makes them easy to overuse. A value that only one method needs should be a local variable; a value a method needs from its caller should be a parameter. Turning locals into fields to avoid passing arguments creates hidden connections between methods and bugs that depend on the order of calls.

Shadowing a field

The no-redeclaring rule applies only among locals. A local variable or parameter may have the same name as a field. Inside its scope, the local shadows the field: the plain name refers to the local. To reach the field, write this.name:

Java A parameter shadowing a field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

setTargetBroken is a classic bug: inside the method, both sides of target = target mean the parameter, so the field never changes. It compiles without error; many IDEs warn about it. The this.target = target; form is the standard idiom in constructors and setters, and you'll use it constantly from Constructors and The this Keyword onward. For static fields, qualify with the class name instead: Main.counter = counter;.

Outside setters and constructors, avoid shadowing on purpose, as report does. Two different variables with the same name in the same method make code hard to read.

Pattern variables and flow scoping

Since Java 16, instanceof can declare a variable: if (obj instanceof String s). The scope of s is unusual: it exists wherever the compiler can prove the test succeeded. This is called flow scoping:

Java Where a pattern variable is in scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In shout, text is in scope after the if, because the only way to get past it is for the test to have succeeded. That's handy for guard clauses. With || instead of &&, the variable isn't in scope on the right side, because that side runs exactly when the test failed. Pattern Matching covers patterns in full.

Lifetime: how long values live

Scope is about names in source code; lifetime is about values at run time. For local variables they line up closely. Each method call gets a frame on the call stack holding its parameters and locals. When the method returns, the frame is discarded, and so are all its locals. That's why recursion works: each call of the same method has its own separate set of locals (Recursion).

Objects are different. An object created with new lives on the heap, and it survives as long as something still refers to it, even after the variable that first held it goes out of scope:

Java
int[] makeSquares(int n) {
    int[] result = new int[n];        // the array lives on the heap
    for (int i = 0; i < n; i++) {
        result[i] = i * i;
    }
    return result;                    // the local "result" dies; the array lives on
}

The local variable result disappears when makeSquares returns, but the array survives because the caller now holds a reference to it. When nothing refers to an object anymore, it becomes eligible for garbage collection, and the JVM reclaims its memory automatically at some later point. Memory and Garbage Collection covers this in depth.

Habits that keep scope clean

  • Declare variables in the smallest scope that works, as close as possible to their first use. A variable that exists only where it's needed can't be misused elsewhere.
  • Initialize at the declaration when you can. String ticket = age < 18 ? "youth" : "adult"; beats a declaration followed by assignments in branches.
  • Prefer locals and parameters over fields for data that one call needs.
  • Use this.field in constructors and setters, and avoid other shadowing.
  • Keep methods short. In a 15-line method, scope problems are hard to create and easy to spot.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens? if (true) { int x = 3; } IO.println(x); (no other x exists)

    x is declared inside the if block, so its scope ends at the closing brace. Declare it before the if to use it afterward.
  2. 2. Which code compiles?

    The two loops' i variables have separate, non-overlapping scopes. The other options redeclare a local or parameter inside its own scope, which Java forbids.
  3. 3. In a compact file, int count; is declared at the top level and void hit() { count++; } is called three times from main. What is count afterward?

    A top-level variable in a compact file is a field. Fields start at their default value (0) and keep their value between calls, so three calls give 3.
  4. 4. A class has a field int size; and a method void setSize(int size) { size = size; }. What does setSize(5) do to the field?

    The parameter shadows the field, so size = size assigns the parameter to itself. Write this.size = size to assign the field.
  5. 5. A method creates an array with new, stores it in a local variable and returns it. What happens to the array when the method returns?

    Locals die with their stack frame, but objects live on the heap as long as something refers to them. The returned reference keeps the array alive.

Summary

  • A local variable's scope runs from its declaration to the end of its enclosing block; inner blocks can see outer variables, but not the reverse.
  • Declare a variable before a block or loop when you need its value afterward; the compiler checks it's definitely assigned before use.
  • Java forbids redeclaring a local or parameter in a nested scope, but sibling blocks can reuse names.
  • Fields are visible in the whole class, have default values and keep their values between method calls; locals are fresh on every call.
  • A local or parameter can shadow a field; use this.field (or ClassName.field for statics) to reach the field.
  • Pattern variables from instanceof are in scope wherever the test is known to have succeeded.
  • Locals live as long as their stack frame; objects live on the heap until nothing refers to them.

Next: Recursion, where a method calls itself and the call stack you've just learned about does the bookkeeping.