Bird
0
0

Consider the following Java code snippet:

medium📝 execution Q13 of 15
Java - Memory Management Basics
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?
ADone
Bhello
CNo output, program crashes
DDone followed by garbage collection logs
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes