Skip to the workspace
Pebellslearn by building
Java Basics  ›  Lesson

Variables and Scope

Variables and Scopes 12 minA variable is a named storage location with a type. Scope determines where its name can be used; a local variable declared in a block is in scope from its declaration through the rest of that block.

java / Variables and Scope

Explore each scene at your own pace.

01 · The rule

The rule

Variables and Scope

A variable is a named storage location with a type. Scope determines where its name can be used; a local variable declared in a block is in scope from its declaration through the rest of that block.

Move a running total to the correct scope and distinguish visibility from object lifetime.

Brew Bar's till adds up an order one drink at a time. The running total must survive the whole calculation, while the price of each drink only matters for a moment. Java decides how long a variable lives by where you declare it, and knowing that rule removes a whole family of "cannot find symbol" errors.

The rule

A variable lives from its declaration to the closing brace of its block.

A variable is a named, typed box. You declare it once, with a type, and can assign new values later:

int totalCents = 0;          // declare and initialise
totalCents = totalCents + 320;
final int MAX_CUPS = 20;     // final: can be assigned only once
var drink = "Mocha";         // var: the compiler infers String

var is only shorthand for local variables. The type is still fixed: the compiler reads it from the value, so drink is a String forever.

A block is any code between { and }: a method body, an if branch, a loop body. Its scope is the region where the name can be used:

int totalCents = 0;
for (int i = 0; i < 3; i++) {
    int priceCents = 320;       // born here, each time round
    totalCents += priceCents;
}                               // priceCents and i end here
System.out.println(totalCents); // 960

Three rules follow from this:

  • Outer names are visible inside. The loop body can use totalCents, declared above it.
  • Inner names vanish outside. After the loop, priceCents and i no longer exist.
  • No reusing a live local name. Declaring another int totalCents inside the loop is a compile error, because the outer one is still in scope.

Local variables also have no default value. Reading one before you assign it is a compile error, not a zero.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.