Java Variable Scope and Garbage Collection (OCP 21)
Scope and object lifetime for the OCP Java 21 exam: block scope for locals, parameters, loop variables, fields and static variables, shadowing and redeclaration rules, when objects become eligible for garbage collection, System.gc(), and why finalize() is obsolete.
kvi5hnuCode Sprout team member8 min readOn this page
Two questions decide whether a lot of exam code compiles and what it does at runtime: Where can this variable be used? and When can this object be thrown away? The first is about scope, a compile-time property of variables. The second is about garbage collection, a runtime property of objects. Keep that split in mind: variables have scope, objects become eligible for collection.
Scope of local variables
A local variable is in scope from its declaration to the end of the block it's declared in. A block is any pair of braces: a method body, an if branch, a loop body or a bare { }.
public void waterIfDry(boolean dry) {
if (dry) {
int cups = 2;
{
boolean small = true;
System.out.println(cups); // OK: inner blocks see outer variables
}
System.out.println(small); // DOES NOT COMPILE: small's block has ended
}
System.out.println(cups); // DOES NOT COMPILE: cups' block has ended
}
Inner blocks can use variables from the blocks around them. Outer blocks can't see into inner ones. A local can never live longer than the method it's declared in.
Some variables are tied to a specific statement:
- A method or constructor parameter is in scope for the whole body.
- A variable declared in a
forloop header, likefor (int i = 0; ...), exists only in that loop. Usingiafter the loop givescannot find symbol. - A variable declared in a
tryblock is out of scope in itscatchandfinallyblocks and after the statement. - A
catchparameter, such aseincatch (Exception e), exists only in itscatchblock.
Tracing scope on the exam
When a question looks complicated, first match up the braces from the inside out, and then note where each variable starts and ends:
31: public void charge(boolean pluggedIn, int minutesLeft) {
32: int battery = 40;
33: if (pluggedIn) {
34: var fastMode = true;
35: while (minutesLeft > 0) {
36: int gain = 3;
37: battery = battery + gain;
38: minutesLeft = minutesLeft - 10;
39: }
40: }
41: System.out.println(minutesLeft);
42: }
| Variable | In scope on lines | Why |
|---|---|---|
pluggedIn, minutesLeft | 31–42 | Parameters cover the whole method |
battery | 32–42 | Declared in the method block |
fastMode | 34–40 | Declared in the if block |
gain | 36–39 | Declared in the while block |
The method compiles, because line 41 uses a parameter. If it printed gain or fastMode instead, it wouldn't.
Redeclaring a name
Java is stricter here than C or C++:
- A local variable can't be redeclared while the first one is still in scope, even in a nested block. That includes clashes with a parameter and with a
forloop variable. - Sibling blocks may reuse a name, because the first variable is gone before the second is declared.
void m(int p) {
int x = 1;
{ int x = 2; } // DOES NOT COMPILE: x is already defined
{ int p = 3; } // DOES NOT COMPILE: p is already defined
for (int x = 0; x < 3; x++) { } // DOES NOT COMPILE
for (int i = 0; i < 3; i++) { }
for (int i = 0; i < 3; i++) { } // OK: the first i is out of scope
int i = 10; // OK, for the same reason
}
A local variable may have the same name as a field. The local then shadows the field inside its scope, and this.name reaches the field. The class design chapter covers this, along with constructors that use this.color = color;.
Scope of fields
The rules for fields are simpler:
| Kind of variable | In scope |
|---|---|
| Local variable | From its declaration to the end of its block |
| Method parameter | The whole method |
| Instance variable | From its declaration, for as long as the object exists |
Class (static) variable | From its declaration, for as long as the class is loaded, usually the whole program |
"From its declaration" matters for fields only in initializers, where forward references are illegal (article 4). Methods can use any field of their class wherever it's declared.
public class Plant {
static final int MAX_HEIGHT = 30; // class variable
int height; // instance variable
public void water(int cm) { // cm: the whole method
if (height < MAX_HEIGHT) {
int newHeight = height + cm; // newHeight: only this if block
height = newHeight;
}
}
}
Garbage collection
Every object lives on the heap. Memory is limited, so the JVM's garbage collector finds objects the program can no longer reach and reclaims their memory. Java has no delete or free. You can't destroy an object yourself.
Eligible is not the same as collected
An object is eligible for garbage collection when no live part of the program can reach it any more. That happens when:
- no reference points to it any more, because every reference was reassigned or set to
null, or - every reference that pointed to it has gone out of scope.
Eligibility is all the exam asks about. When an eligible object is actually collected, or whether it ever is, is up to the JVM. A short program may finish without collecting anything.
System.gc() (and Runtime.getRuntime().gc()) only suggests that the JVM run a collection. It may do nothing. The JVM can even be started with -XX:+DisableExplicitGC to ignore it completely. On the exam, System.gc() never guarantees that anything is collected.
Draw the references
For eligibility questions, write each variable name and draw an arrow to the object it refers to. Each time a reference changes, move its arrow. An object with no arrows left is eligible.
1: Cup a = new Cup("red");
2: Cup b = new Cup("blue");
3: Cup c = a;
4: a = b;
5: c = null;
6: b = null;

- After line 4,
"red"is still reachable throughc. - After line 5, nothing points to
"red", so it becomes eligible here, not at line 4. - After line 6,
"blue"is still reachable througha. It becomes eligible only whenagoes out of scope or is reassigned.
Note that line 3 copies a reference, not an object. c = a makes c point to the object a points to at that moment. Changing a later doesn't move c.
Islands of isolation
Objects that refer to each other but can't be reached from the program are still eligible:
Node x = new Node();
Node y = new Node();
x.next = y;
y.next = x; // a cycle
x = null;
y = null; // both nodes are now unreachable, so both are eligible
Collectors in the JVM trace reachability from roots (local variables on the stacks of live threads, static fields and a few others). They don't count references, so a cycle doesn't keep anything alive.
What's current
- Scope rules and garbage-collection eligibility are unchanged through Java 25.
finalize()is deprecated for removal (JEP 421). G1 is still the default collector, and ZGC has run only in generational mode since Java 24.
Exam traps from this article
A complete example
public class Solution {
static final int MAX_CUPS = 3; // class variable: in scope for the whole program
private final String color; // instance variable: lives as long as its object
private Solution partner; // lets us build a cycle of references
Solution(String color) {
this.color = color;
}
static void scopeDemo(boolean hungry) { // parameter: in scope for the whole method
int served = 0; // local: from here to the end of the method
if (hungry) {
int extra = 2; // local to the if block
served += extra;
{
boolean tiny = true; // local to this inner block
System.out.println("inner block sees served=" + served + ", tiny=" + tiny);
}
// tiny is out of scope here
}
// extra is out of scope here
for (int i = 0; i < MAX_CUPS; i++) {
served++; // i exists only inside the loop
}
System.out.println("served=" + served);
}
public static void main(String[] args) {
scopeDemo(true);
Solution a = new Solution("red"); // object R
Solution b = new Solution("blue"); // object B
Solution c = a; // two references to R
a = b; // R still reachable through c
System.out.println("c still reaches " + c.color);
c = null; // nothing refers to R: it is now eligible for GC
b = null; // B is still reachable through a
System.out.println("a still reaches " + a.color + ", b is " + b);
Solution x = new Solution("green");
Solution y = new Solution("yellow");
x.partner = y;
y.partner = x; // a cycle: each refers to the other
System.out.println(x.color + " <-> " + x.partner.color);
x = null;
y = null; // the cycle is unreachable, so both are eligible
System.gc(); // only a request: the JVM may ignore it
System.out.println("done");
}
}
Output:
inner block sees served=2, tiny=true
served=5
c still reaches red
a still reaches blue, b is null
green <-> yellow
done
The output never shows garbage collection itself, and that's deliberate. Whether and when collection happens isn't specified, so any program whose output depended on it would be unreliable. The comments mark the points where objects become eligible, and that's what the exam asks about.
Common questions
Does setting a variable to null free memory immediately?
No. It removes one reference. If that was the last reference, the object becomes eligible, and the collector reclaims it whenever it decides to run.
Is an object eligible as soon as its method's last line that uses it has run? For exam purposes, a local variable keeps its object reachable until the variable goes out of scope or is reassigned. (A real JIT compiler may treat an unused local as dead earlier, but the exam uses the scope rule.)
Can a static variable keep an object alive forever?
Yes, as long as the class stays loaded. A static collection that keeps growing is a classic memory leak in Java.
Why can't I declare int x in a nested block when an outer x exists?
The language forbids a local from shadowing another local that's still in scope, to prevent confusing bugs. Locals may shadow fields, and sibling blocks may reuse a name.
Can I force garbage collection for testing?
Not reliably. System.gc() is a hint. Tools such as jcmd <pid> GC.run also only request a collection. Tests should never depend on collection timing.
What happens when the heap is full and nothing is eligible?
The JVM throws OutOfMemoryError, an Error that programs normally don't catch.
Summary
- A local variable is in scope from its declaration to the end of its block. A parameter covers its method. A
forloop variable covers only its loop. - Inner blocks see outer variables, but not the other way round. A local can't be redeclared while it's in scope. Sibling blocks can reuse names.
- Instance variables live as long as their object, and class variables as long as their class is loaded.
- An object is eligible for garbage collection when nothing reachable refers to it, including unreachable cycles. Whether and when it is collected is up to the JVM.
System.gc()is only a suggestion.finalize()is deprecated for removal, so usetry-with-resources orCleaner.
Practice quiz
Test yourself with the variable scope and garbage collection quiz: 10 exam-style questions with explanations. Then take the Chapter 1 review: 20 mixed questions across the whole chapter.
Previous: Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
Next: Java Operators: Types, Precedence and Unary Operators (OCP 21)
Related reading
- Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet
- Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations
- Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
- Java Maps: HashMap, TreeMap and Updating Map Entries

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.