Scope and Local Variables

Where a variable is declared decides where it can be used and how long it lasts. A juice bar's Juicer keeps a running total of the juice it has made, in milliliters.
public class Juicer
{
private int totalMl;
public void press(int oranges)
{
int ml = oranges * 60;
totalMl = totalMl + ml;
}
public int getTotalMl()
{
return totalMl;
}
}
The instance variable totalMl is declared outside every method, so it is visible to any constructor and to all of the instance methods, and its value carries over between calls. The variable ml is declared inside press. It's a local variable: it exists only while press runs, and getTotalMl can't use it. The parameter oranges is a local variable too. It gets its first value from the argument, and it also disappears when the call ends.
Blocks
A block is the code between a pair of matching braces: a method body, the body of an if, the body of a loop. A variable declared in a block stops existing at the brace that closes the block.
for (int glass = 1; glass <= 3; glass++)
{
int pour = 180 + glass * 10;
System.out.println(pour);
}
System.out.println(pour);
The last line doesn't compile, since pour was declared inside the loop's braces. A new pour is created on each pass, so the loop prints 190, 200, and 210 using three separate variables. The same goes for glass, the variable the for header creates.
Two blocks that don't contain each other can use the same name for different variables. Each branch of an if-else can declare its own int cups, since neither branch's block contains the other. A block inside another can't redeclare a local name the outer block already uses.
A local must be assigned
An instance variable that nothing has assigned holds its default value, so an int instance variable starts at 0. A local variable has no default.
public void press(int oranges)
{
int ml;
totalMl = totalMl + ml;
}
This doesn't compile, because ml is read before anything has been stored in it. Writing private int ml; inside the method doesn't fix it either. An access modifier on a local variable is itself a compile error, since no code outside the method could reach the variable anyway.