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 Stringvar 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); // 960Three 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,
priceCentsandino longer exist. - No reusing a live local name. Declaring another
int totalCentsinside 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.
Find the job
We need the total after the loop, to print it.
Drills
Answer fast — trust the rule.
The loop above is followed by System.out.println(priceCents);. What happens?
What happens with var cups = 2; followed later by cups = 2.5;?
Inside main, int points; is followed immediately by System.out.println(points);. What happens?
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.
