OCP exam prep: garbage collection¶
☕ Java 17 · 🎓 OCP 1Z0-829 · Destroying Objects and Memory Management
Optional page
This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.
Four traps to watch for¶
Trap 1 — System.gc() guarantees nothing
It's a hint the JVM may ignore. After the call, assume nothing about what was collected.
Trap 2 — Multiple references keep an object alive
Series s2 = s1; s1 = null; — s2 still reaches the object, so it's not eligible.
Trap 3 — Reassignment is enough
m = new Movie("Avatar"); makes the previous object unreachable, even though m was never set to null.
Trap 4 — Locals die at the closing brace
When a method ends, all its local variables go out of scope at once, and the objects only they referenced become eligible.
Practice questions¶
1. At which line does the "Inception" object first become eligible for garbage collection?
1: Movie a = new Movie("Inception");
2: Movie b = new Movie("Parasite");
3: Movie c = a;
4: a = b;
5: c = null;
6: b = null;
A. Line 3
B. Line 4
C. Line 5
D. Line 6
Answer
C. After line 3, a and c both reach "Inception". Line 4 moves a to "Parasite", but c still holds "Inception". Line 5 removes that last reference.
2. Which statements are correct? (Choose all that apply.)
public static void main(String[] args) {
User user = new User("alice@netflix.com");
Subscription sub = new Subscription(user);
user = null; // Line X
}
A. The User object is eligible for GC at Line X
B. System.gc() guarantees the User object is collected immediately
C. The User object may not be eligible at Line X if sub keeps a reference to it
D. Garbage collection is guaranteed to run before the program ends
Answer
C only. If the Subscription constructor stores the user in a field, sub still reaches it, so A can't be asserted. System.gc() guarantees nothing, and the collector may never run at all.