A local shadowing a static field
A variable's scope is the part of the code where its name can be used; its lifetime is how long its storage exists while the program runs. Locals live in a block and die with their method call, fields live as long as their object, and static fields live as long as their class.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a program with a static field nextId starting at 1 and a method static int newId() that returns the current id and increases it. Call it three times and print the ids.
Fix this so it compiles and prints the largest value: int max; for (int v : new int[] {3, 8, 5}) { if (v > max) max = v; } System.out.println(max);
Write a method that uses two separate for loops, both with a variable named i, to print 0 1 2 and then 2 1 0 on two lines.
Explain it without notes
What is the difference between scope and lifetime? Give an example where they differ.
Why does a local variable used as a counter start again from zero on every call?
Why does Java refuse to compile a read of an unassigned local, but allow reading an unassigned field?
What is shadowing, and how do you reach a shadowed static field?
Expected output
plain count = 5
Main.count = 10
plain count = 10
defaults = 0, 0