Bird
0
0

What will be printed when the following Java program runs?

medium📝 Predict Output Q4 of 15
Java - Memory Management Basics
What will be printed when the following Java program runs?
public class DemoGC {
  public static void main(String[] args) {
    DemoGC instance = new DemoGC();
    instance = null;
    System.gc();
    System.out.println("Program finished");
  }
}
ANullPointerException
BProgram finished
CNo output
DGarbage collection completed
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the code

    The program creates an object, sets its reference to null, calls System.gc(), then prints "Program finished".
  2. Step 2: Understand System.gc()

    System.gc() is a request to JVM; it does not guarantee immediate garbage collection or affect output.
  3. Step 3: Determine output

    The only output is the print statement, so "Program finished" is printed.
  4. Final Answer:

    Program finished -> Option B
  5. Quick Check:

    System.gc() does not block or change print output [OK]
Quick Trick: System.gc() does not affect immediate output [OK]
Common Mistakes:
  • Expecting System.gc() to print messages
  • Assuming garbage collection throws exceptions
  • Thinking no output means program failure

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes