Skip to content

Blocks define scope

โ˜• Java 17 ยท Managing Variable Scope ยท 1/3

Three levels in one class

public class StreamingPlatform {
    String name = "Netflix";          // field

    public void launch() {
        int users = 1000;             // local variable
        if (users > 500) {
            int bonus = 50;           // block variable
        }
        // bonus doesn't exist here
        System.out.println(users);
    }
}
Variable Scope
name (field) the whole class: every method can use it
users (local) from its declaration to the end of launch()
bonus (block) only inside the if braces

A block is a pair of braces

Every { opens a new scope region; the matching } closes it. A variable declared inside belongs to that region only:

public void stream(boolean hungry) {
    if (hungry) {
        int snacks = 3;
        snacks++;
    }
    System.out.println(snacks);    // โŒ doesn't compile: snacks is out of scope
    System.out.println(hungry);    // โœ… a parameter lives for the whole method
}

Like nesting dolls:

  • an inner block can read the variables of the blocks around it,
  • an outer block can't see what's declared inside an inner block.

Once a block closes, its variables are gone for the compiler too: using them is a compile error, not a runtime one.

Method parameters behave like local variables declared at the very top of the method: in scope for the whole body, and nowhere else.

No redeclaring a name in a nested block

Java forbids declaring a variable in an inner block with the same name as one still in scope:

public void playMovie(boolean vip) {
    int maxStreams = 3;
    if (vip) {
        int maxStreams = 5;        // โŒ already defined in this method
    }
}

Some languages allow this "shadowing" of locals; Java doesn't. Once the outer variable's scope ends, though, the name is free again:

if (vip) {
    int bonus = 5;
}
int bonus = 0;                     // โœ… the first bonus is already out of scope

Loops add one more twist: their variables come and go on every iteration.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

Next: scope in loops โ†’