Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Java Basics  ›  Lesson

Variables and Scope

Variables and Scopes 12 minA variable is a named, typed box that exists only from its declaration to the end of the block that contains it.

Variables and Scope

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.

The shortcut

Put your finger on a variable's declaration and slide down to the } that closes that block. That stretch is where the name exists. Anything using it outside the stretch will not compile.

Why the till total goes outside the loopStep 1 of 4
  1. Find the job

    We need the total after the loop, to print it.

Drills

Answer fast — trust the rule.

quick drill

The loop above is followed by System.out.println(priceCents);. What happens?

quick drill

What happens with var cups = 2; followed later by cups = 2.5;?

quick drill

Inside main, int points; is followed immediately by System.out.println(points);. What happens?

quick drill

int cups = 1; then if (cups > 0) { int cups = 2; } in the same method. What happens?

Remember

  • A variable lives from its declaration to the closing brace of its block.
  • Slide your finger from the declaration to that brace; that is the scope.
  • Traps: declaring a total inside the loop, and reading a local before it has a value.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe total that keeps resetting

A student writes a loop over three drinks and declares int totalCents = 0; as the first line inside the loop body, then tries to print totalCents after the loop. Explain both problems this causes and how moving one line fixes them.