Challenge - 5 Problems
Garbage Collection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediateWhat is the primary purpose of garbage collection in Java?
Choose the best description of what garbage collection does in Java.
Attempts:
2 left
💡 Hint
Think about how Java manages memory without programmer intervention.
✗ Incorrect
Garbage collection automatically frees memory by removing objects that are no longer reachable, helping prevent memory leaks.
❓ query_result
intermediateWhat output does this code produce regarding object finalization?
Consider the following Java code snippet. What will be printed when the program runs?
Java
class Test { protected void finalize() { System.out.println("Finalized"); } public static void main(String[] args) { Test t = new Test(); t = null; System.gc(); System.out.println("End of main"); } }
Attempts:
2 left
💡 Hint
Garbage collection and finalization timing is not guaranteed immediately after System.gc().
✗ Incorrect
Calling System.gc() suggests garbage collection but does not guarantee immediate finalization. The program prints "End of main" and may finalize later.
📝 Syntax
advancedIdentify the syntax error in this garbage collection related code snippet
Which option contains a syntax error preventing compilation?
Java
public class GCExample { public static void main(String[] args) { Object obj = new Object(); obj = null; System.gc(); } }
Attempts:
2 left
💡 Hint
Check method declaration syntax in Java.
✗ Incorrect
Method declarations must include a return type. Option A lacks a return type, causing a syntax error.
❓ optimization
advancedWhich approach helps reduce garbage collection overhead in Java?
Select the best practice to minimize the impact of garbage collection on application performance.
Attempts:
2 left
💡 Hint
Think about how object reuse affects memory and garbage collection frequency.
✗ Incorrect
Reusing objects reduces the number of new objects created, lowering the frequency and cost of garbage collection.
🔧 Debug
expertWhy does this Java program cause a memory leak despite garbage collection?
Examine the code below and select the reason it causes a memory leak.
Java
import java.util.ArrayList; public class LeakExample { static ArrayList<Object> list = new ArrayList<>(); public static void main(String[] args) { while(true) { Object obj = new Object(); list.add(obj); } } }
Attempts:
2 left
💡 Hint
Consider what keeps objects reachable and how that affects garbage collection.
✗ Incorrect
Storing objects in a static list keeps references alive, so garbage collector cannot free them, causing a memory leak.
