Bird
Raised Fist0
Javaprogramming~20 mins

Garbage collection overview in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Garbage Collection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the primary purpose of garbage collection in Java?
Choose the best description of what garbage collection does in Java.
APrevents the creation of new objects to save memory.
BManually deletes objects when the programmer calls a delete method.
CAutomatically frees memory by removing objects that are no longer reachable.
DOptimizes CPU usage by pausing all running threads.
Attempts:
2 left
💡 Hint
Think about how Java manages memory without programmer intervention.
❓ query_result
intermediate
2:00remaining
What 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");
  }
}
AEnd of main
B
Finalized
End of main
C
End of main
Finalized
DNo output
Attempts:
2 left
💡 Hint
Garbage collection and finalization timing is not guaranteed immediately after System.gc().
📝 Syntax
advanced
2:00remaining
Identify 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();
  }
}
Afinalize() { System.out.println("Cleaning up"); }
Bprotected void finalize() { System.out.println("Cleaning up"); }
Cvoid finalize() { System.out.println("Cleaning up"); }
Dpublic void finalize() { System.out.println("Cleaning up"); }
Attempts:
2 left
💡 Hint
Check method declaration syntax in Java.
❓ optimization
advanced
2:00remaining
Which approach helps reduce garbage collection overhead in Java?
Select the best practice to minimize the impact of garbage collection on application performance.
ACreate many short-lived objects frequently to keep memory usage high.
BAvoid using local variables to reduce memory allocation.
CCall System.gc() explicitly after every object creation.
DReuse objects when possible instead of creating new ones repeatedly.
Attempts:
2 left
💡 Hint
Think about how object reuse affects memory and garbage collection frequency.
🔧 Debug
expert
3:00remaining
Why 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);
    }
  }
}
AThe infinite loop causes the program to crash before garbage collection can run.
BObjects are never dereferenced because they are stored in a static list, preventing garbage collection.
CSystem.gc() is not called, so garbage collection never happens.
DThe Object class does not support garbage collection.
Attempts:
2 left
💡 Hint
Consider what keeps objects reachable and how that affects garbage collection.

Practice

(1/5)
1. What is the main purpose of garbage collection in Java?
easy
A. Increase the size of the heap memory
B. Automatically free memory used by objects no longer needed
C. Manually delete objects from memory
D. Compile Java code into bytecode

Solution

  1. Step 1: Recall the purpose of garbage collection and evaluate options

    Garbage collection automatically frees memory used by objects that are no longer referenced in the program. Only "Automatically free memory used by objects no longer needed" matches this definition.
  2. Final Answer:

    Automatically free memory used by objects no longer needed -> Option B
  3. Quick Check:

    Garbage collection = automatic memory freeing [OK]
Hint: Garbage collection frees unused memory automatically [OK]
Common Mistakes:
  • Thinking garbage collection deletes objects manually
  • Confusing garbage collection with compiling code
  • Believing it increases heap size
2. Which of the following is the correct way to suggest garbage collection in Java?
easy
A. GarbageCollector.run()
B. System.collect()
C. Runtime.gcCollect()
D. System.gc()

Solution

  1. Step 1: Recall and verify the method to suggest garbage collection

    Java provides System.gc() to suggest that the JVM runs garbage collection. Only System.gc() is a valid Java method; the others are incorrect or do not exist.
  2. Final Answer:

    System.gc() -> Option D
  3. Quick Check:

    Suggest GC = System.gc() [OK]
Hint: Use System.gc() to suggest garbage collection [OK]
Common Mistakes:
  • Using System.collect() which does not exist
  • Confusing Runtime methods with System methods
  • Assuming garbage collection runs immediately after calling System.gc()
3. Consider the following Java code snippet:
public class TestGC {
  public static void main(String[] args) {
    String s = new String("hello");
    s = null;
    System.gc();
    System.out.println("Done");
  }
}

What is the expected output when this code runs?
medium
A. Done
B. hello
C. No output, program crashes
D. Done followed by garbage collection logs

Solution

  1. Step 1: Trace code execution and determine output

    The string object "hello" is created, then the reference s is set to null, making it eligible for GC. System.gc() suggests collection but does not guarantee immediate action or logs. The only guaranteed output is "Done" from the print statement.
  2. Final Answer:

    Done -> Option A
  3. Quick Check:

    Print statement output = Done [OK]
Hint: System.gc() does not print anything; only explicit prints show [OK]
Common Mistakes:
  • Expecting garbage collection logs to print automatically
  • Thinking the string "hello" prints after null assignment
  • Assuming program crashes due to null reference
4. Identify the error in the following Java code related to garbage collection:
public class GCExample {
  public static void main(String[] args) {
    Object obj = new Object();
    obj = null;
    System.gc;
  }
}
medium
A. Cannot assign null to an Object
B. Object cannot be garbage collected
C. Missing parentheses in System.gc call
D. System.gc is not a valid method

Solution

  1. Step 1: Locate the syntax error in the code

    System.gc is a method call requiring parentheses (System.gc()); the code has System.gc without them, causing a compilation error. Assigning null to Object and the method's existence are valid.
  2. Final Answer:

    Missing parentheses in System.gc call -> Option C
  3. Quick Check:

    Method calls need parentheses [OK]
Hint: Always use parentheses when calling methods like System.gc() [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Thinking null assignment is invalid
  • Believing System.gc is not a method
5. You have a Java program that creates many temporary objects inside a loop. Which approach best helps ensure efficient memory use with garbage collection?
hard
A. Set object references to null when no longer needed inside the loop
B. Call System.gc() inside every loop iteration
C. Increase heap size to avoid garbage collection
D. Avoid creating any objects inside the loop

Solution

  1. Step 1: Identify best practice for efficient memory use in loops

    Many temporary objects in a loop can pressure memory; explicitly setting references to null when no longer needed helps the GC identify and free them sooner. Frequent System.gc() is inefficient and not guaranteed; larger heap delays issues; avoiding all objects may not be feasible.
  2. Final Answer:

    Set object references to null when no longer needed inside the loop -> Option A
  3. Quick Check:

    Null references help GC free memory efficiently [OK]
Hint: Nullify unused references to help garbage collection [OK]
Common Mistakes:
  • Calling System.gc() too often expecting instant cleanup
  • Thinking increasing heap size solves memory leaks
  • Believing you must avoid all object creation in loops
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard