Lesson Overview
Manage where names are visible, how long values live and why smaller scope usually makes code easier to reason about.
Portfolio focus: Mark every variable in a small program as local variable, parameter or field.
Starter: think before typing
Before running this maintainable state example, find the line where the main idea becomes active. Write a prediction: what must already be true for that line to work, and what should be different after it runs? The checked run ends with `Total mark: 218`; predict how the focus line helps produce that evidence.
Learning Objectives
- Distinguish local variables from fields.
- Explain why scope controls identifier availability.
- Describe object lifetime in ordinary Java programs.
- Reduce unnecessary shared state.
Learning Outcomes
- By the end of the lesson, you can distinguish local variables from fields.
- By the end of the lesson, you can explain why scope controls identifier availability.
- By the end of the lesson, you can describe object lifetime in ordinary Java programs.
- By the end of the lesson, you can reduce unnecessary shared state.
Why this idea exists
Scope exists because not every name should be visible everywhere. Limiting where a variable can be used reduces accidental coupling and makes it easier to see which part of the program owns a piece of information.
Lifetime is the related question of how long a value or object remains useful. Earlier languages made memory lifetime very explicit; Java hides much of the memory management, but programmers still need to reason about when values are created, shared and no longer needed.
This topic fits the arc after program structure because it teaches restraint. Good scope choices make methods safer, objects cleaner and debugging easier because less state is available to change accidentally.
Deep dive
Mechanism in this example
The important mechanism is visible around `int total = 0;`. Read it as a concrete move in the program, not as decorative syntax: identify what value, object, branch, call or boundary is being created at that point.
Design pressure
This topic fits the arc after program structure because it teaches restraint. Good scope choices make methods safer, objects cleaner and debugging easier because less state is available to change accidentally.
Failure mode to watch
For Scope and Lifetime, deliberately disturb the assumption behind `int total = 0;`: use an awkward value, missing input, wrong order of calls or boundary case. The useful question is how that disturbance exposes a weakness in the maintainable state design.
Extension step
Extend the example by doing this: Move one variable into a smaller scope. The point is to make one small change that forces you to revisit the concept, rather than adding unrelated features.
Portfolio standard
The portfolio note should not repeat the lesson wording. It should show the edited code, the run result, and your own explanation of this evidence: explain how smaller scope reduces accidental coupling.
Lesson visual

Type this and run it
Create ScopeAndLifetimeDemo.java, type the program, and run it before changing anything. This section is about reproducing the checked baseline.
public class ScopeAndLifetimeDemo {
public static void main(String[] args) {
int[] marks = {72, 65, 81};
int total = 0;
for (int mark : marks) {
total = total + mark;
}
System.out.println("Total mark: " + total);
}
}Build and run it with:
javac ScopeAndLifetimeDemo.java && java ScopeAndLifetimeDemoExpected baseline: Total mark: 218
Run the code in your browser
Use the editor as an experiment surface. First run the checked version, then make one small change to the part of the program that demonstrates maintainable state and compare the new behaviour with the reference output.
Total mark: 218Line-by-line explanation
Read the code as a sequence of responsibilities. The focus line for this lesson is int total = 0;; the surrounding lines prepare it, use its result or make the behaviour observable.
public class ScopeAndLifetimeDemo {This names the runnable class for the Scope and Lifetime example, giving the compiler and JVM one clear unit to build.
public static void main(String[] args) {This is the program entry point. In Scope and Lifetime, it keeps the demonstration of maintainable state in one traceable starting script.
int[] marks = {72, 65, 81};This introduces marks as named state for Scope and Lifetime. Later lines can read, update, pass or print that specific value as evidence.
int total = 0;This introduces total as named state for Scope and Lifetime. Later lines can read, update, pass or print that specific value as evidence.
for (int mark : marks) {This starts repetition in Scope and Lifetime. Check the initial value, the stopping condition and the update on each pass.
total = total + mark;This assignment changes total in Scope and Lifetime to total + mark. Trace where that new value is used next.
}This closes the innermost Scope and Lifetime block, so the immediately preceding method, branch or loop has finished.
System.out.println("Total mark: " + total);This prints "Total mark: " + total as the observable evidence for Scope and Lifetime. The output lets the learner check whether the maintainable state idea behaved as predicted.
}This closes the outer Scope and Lifetime structure, returning the reader to the surrounding class or file.
}This closing brace number 3 completes another layer of the Scope and Lifetime source structure Java has been checking.
Worked example
From code to explanation
Problem: Use Scope and Lifetime to complete a small portfolio-quality step: Mark every variable in a small program as local variable, parameter or field.
Method: Locate the line `int total = 0;`, explain the exact role it plays, then decide what you would change to extend the example without changing the whole program.
Reveal worked answer
The checked run should produce `Total mark: 218`. A strong answer links the result back to maintainable state: what was created, selected, stored, called or protected, and why that matters for the portfolio task.
Trace the program
Before: Before the key operation, identify the relevant value, object, branch or resource that the maintainable state concept depends on.
During: Trace `int total = 0;` as the Scope and Lifetime example executes. Say whether that operation creates data, checks a condition, calls behaviour, stores information or crosses a boundary.
After: Compare the run with the expected evidence: `Total mark: 218`.
Change: Now move one variable into a smaller scope, run again, and explain the smallest reason the behaviour changed.
Common misconception
A common mistake in scope and lifetime is treating the example as a finished answer. For maintainable state, the important question is narrower: which operation carries the idea, what does it make possible, and what would break if you changed it carelessly?
Quick checks
1. In this Scope and Lifetime example, what is the best reason to focus on `int total = 0;`?
2. Which evidence is strongest after you edit and rerun this example?
How to study this lesson
For Scope and Lifetime, predict how maintainable state changes the run before you press Run.
Use the first portfolio task as your main edit: Mark every variable in a small program as local variable, parameter or field.
Use the second task as your variation: Move one variable into a smaller scope.
Finish with evidence, not a diary entry: Explain how smaller scope reduces accidental coupling.
Portfolio Practice
- Mark every variable in a small program as local variable, parameter or field.
- Move one variable into a smaller scope.
- Explain how smaller scope reduces accidental coupling.
Final self-check
Can you explain the key operation?
Explain the line identified in the quick check in one or two sentences. Your answer should say what it does before the output Total mark: 218 appears.
Can you justify the portfolio evidence?
Your evidence should include the original run, one edited run, and a short note explaining how the edit affected maintainable state.
Study route
Practise maintainable state by predicting the Java example, typing it, running it in the browser, tracing the result and saving portfolio evidence.
Next, move into The Array and carry forward one improvement from this lesson into the next program.
