Locals, var and final
Fields get a default and locals do not — that is a compile error, and a good one. Plus what `final` actually freezes.
A local variable is one declared inside a method. It lives on the stack, it dies when the method returns, and it behaves differently from a field in one way that catches everybody exactly once.
Fields get a default. Locals do not.
static int field; // never assigned
static String name; // never assigned
public static void main(String[] a) {
int local;
System.out.println(local); // ?
}The fields are fine:
an unassigned FIELD int = 0
an unassigned FIELD String = nullThe local is not — and the failure is at compile time, not run time:
Unassigned.java:4: error: variable local might not have been initialized
System.out.println(local);
^This is definite assignment, and it is one of the better decisions in the language. An object's fields must have some value the moment the object exists, so Java picks zero, false or null. A local has no such moment — so instead of inventing a value, the compiler refuses to let you read one you never wrote.
The consequence worth internalising: a local variable never silently holds a surprising zero. Whole categories of bug that exist in other languages do not exist here, and it costs you nothing but declaring things when you have a value for them.
Declare it where you use it
The style that survives is: declare a variable in the smallest block that needs it, as late as possible, and assign it immediately.
// what old code looks like: everything declared at the top
int total, count, i;
String name;
// ...forty lines...
// what reads well
int total = 0;
for (Order order : orders) {
int amount = order.amount(); // exists only inside the loop
total += amount;
}The reason is not tidiness. A variable declared forty lines before its use is a variable that can be reused for something else in between, and that is how a loop counter ends up holding a customer id. Narrow scope makes the mistake impossible rather than unlikely, which is the same argument the blocks section made from the compiler's side.
It is also why for (int i = ...) declares i in the header: outside the loop, i does not exist and cannot be read by accident.
var says less, not nothing
Since Java 10 a local may have its type inferred:
var orders = new ArrayList<Order>(); // ArrayList<Order>
var total = 0; // int
var name = customer.getName(); // String? something else? read onThe variable is still statically typed — var is not a dynamic type, and the type is fixed at the declaration. It only removes the need to write it down.
The useful rule is about the reader, not the compiler: use var when the type is obvious from the right-hand side. new ArrayList<Order>() says it. customer.getName() does not — the reader now has to go and look. Locals only; var is not allowed on fields, parameters or return types, which keeps it out of the places where a written type is part of the contract.
final, and what a constant really is
final on a local means the variable may be assigned once:
final int limit = 10;
limit = 20; // does not compileThat is all it means, and the distinction the next example draws is one of the most commonly misunderstood things in Java:
final StringBuilder sb = new StringBuilder("hello");
sb.append(" world"); // allowed
sb = new StringBuilder(); // does not compilefinal reference, mutated = hello worldfinal freezes the reference, not the object. The variable will always point at that same StringBuilder; the StringBuilder itself can change all day. For immutability you need a type that does not let you change it — String, List.copyOf(...), a record of immutable components — and final is not a substitute.
A constant, in the sense people usually mean, is the combination:
private static final int MAX_RETRIES = 3;static— one per class, not one per instance.final— assigned once.SCREAMING_SNAKE_CASE— the convention that says constant to a reader.- A primitive or a genuinely immutable type — because
private static final List<String> NAMES = new ArrayList<>();is a shared mutable list wearing the wordfinal, and anyone can add to it.
final on parameters and the compiler's view
Marking a parameter final prevents reassigning it inside the method. It is a matter of taste — some teams require it, most do not — and the honest summary is that it prevents a mistake nobody makes often.
What is not a matter of taste: a final on a primitive with a compile-time constant value is inlined by the compiler. static final int MAX = 3 is baked into every class that uses it, which means changing it requires recompiling those classes and not just this one — a real source of confusion when one jar is rebuilt and another is not.
And one practical use: a local captured by a lambda or an anonymous class must be final or effectively final — assigned once, whether or not the word is written. That rule is why a loop counter cannot be captured directly, and why the fix is to copy it into a new local inside the loop.
Under the hood: what a local variable actually is in a running method
The stack lesson in the programming-foundations course already established where a local lives — the stack, one frame per call. What that frame actually holds, for locals, is a small fixed-size array of numbered slots (JVMS §2.6.1): javac assigns each local a slot index at compile time — parameters first, then locals in roughly declaration order — and every read or write of that local compiles to an instruction naming the slot directly (iload_0, istore_1), the way the bytecode lesson's javap -c output shows. A method's frame is created fresh, with its own private slot array, on every single call — recursive or concurrent — and discarded the instant the method returns.
That mechanism is why a local needs no lock and is invisible across threads without deliberate sharing, not merely a rule stated on top of it: two threads calling the same method each get their own frame, with their own slot array, on their own stack. There is no shared slot 1 for them to race on — "thread A's total" and "thread B's total" are different memory locations by construction, occupying the same slot number in two entirely separate frames. A field or a static works the other way: one storage location, shared by every thread that reaches it, which is exactly why the concurrency course's memory-model lesson has real content to teach about fields and none at all about locals.
List<Supplier<Integer>> suppliers = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int copy = i;
suppliers.add(() -> copy);
}
for (Supplier<Integer> s : suppliers) {
System.out.println(s.get());
}Each lambda prints a different number, even though all three were created by the same loop and all three run after the loop has finished — by which point i's own frame slot is long gone. The reason is what "effectively final" is actually for: a lambda cannot reach into the enclosing method's stack frame at all, because that frame may not even exist anymore by the time the lambda runs (exactly the situation here — main's loop has moved on, and would eventually return). So the compiler does not let a lambda capture the variable; it captures the value, copied into the lambda object at the point the lambda is created — which only produces a well-defined, single value to copy if the variable is never reassigned after that point. copy is a fresh local created on each iteration, assigned once, so there is exactly one value to copy each time. i itself would fail to compile as a capture for the identical reason a final violation fails: the compiler cannot point at one value that "the variable i" means, because i keeps changing after any lambda that captured it would run.
Try it yourself
Predict the capture, then break it
import java.util.List;
import java.util.ArrayList;
import java.util.function.Supplier;
List<Supplier<Integer>> suppliers = new ArrayList<>();
int i = 0;
while (i < 3) {
int copy = i;
suppliers.add(() -> copy);
i++;
}
for (Supplier<Integer> s : suppliers) {
System.out.println(s.get());
}Before running it: does this print the same three numbers as the for-loop version above, or something different? Then try changing suppliers.add(() -> copy); to suppliers.add(() -> i); without changing anything else, and explain — in terms of slots and frames, not just "the compiler complains" — why that one edit stops compiling.
Answer
Same output, 0 then 1 then 2 — a while loop with a fresh int copy = i; inside it creates a new local (a logically distinct slot binding) on every pass, exactly like the for loop, so the mechanism is identical even though the loop syntax is not. Capturing i directly fails to compile because i is declared outside the loop body and assigned on every iteration (i++) — there is no single value the lambda could copy that would remain correct after the loop moves on, so it is not effectively final, and the compiler rejects it at the capture site rather than let the lambda later read a frame slot that no longer means what it meant when the lambda was created.
Misconceptions
- "A local variable capture keeps a live link to the original variable." It copies the value once, at the point the lambda is created. A later change to what the value would have been — impossible here anyway, since capture requires effectively final — never reaches an already-created lambda.
- "
finalon a local is about thread safety." It is about definite, single assignment, checked at compile time — it says nothing about visibility between threads. Afinalfield on an object shared across threads gets a real visibility guarantee from the Java Memory Model (the concurrency course covers it); afinallocal never crosses a thread boundary to need one, because each thread has its own frame.
Sources
- The Java Virtual Machine Specification, §2.6.1 (Local Variables) — locals as a numbered slot array in each frame.
- The Java Language Specification, §4.12.4 (final Variables) and §15.27.2 (Lambda Body) — effectively final and what a lambda may capture.