Command Palette

Search for a command to run...

Back to the lesson: Topic 3.6 — Scope and Lifetime of Variables
Core Java · Example 1 of 3

Block scope in action

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.

01

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.

02

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);

03

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

01

What is the difference between scope and lifetime? Give an example where they differ.

02

Why does a local variable used as a counter start again from zero on every call?

03

Why does Java refuse to compile a read of an unassigned local, but allow reading an unassigned field?

04

What is shadowing, and how do you reach a shadowed static field?

Block scope in action
Sign in to run this example in your browser.

Expected output

i = 1, square = 1
i = 2, square = 4
i = 3, square = 9
inner temp = 42
outer temp = 7, total = 14