Difficulty: Easy
Correct Answer: Only the garbage collection system can destroy an object.
Explanation:
Introduction / Context:
Unlike languages with explicit deallocation (e.g., C with free, C++ with delete), Java relies on automatic garbage collection. Understanding what APIs do and do not guarantee is critical for correct reasoning about object lifetime.
Given Data / Assumptions:
Concept / Approach:
Java objects are destroyed only by the garbage collector when they become unreachable from GC roots. Methods like System.gc()
or Runtime.getRuntime().gc()
merely request a GC; they do not guarantee immediate collection. The finalize()
method (now deprecated) is a callback that may run prior to collection; calling it directly does not collect an object. There is no delete()
in Java.
Step-by-Step Reasoning:
Verification / Alternative check:
Empirical tests show that calling System.gc()
may not trigger a collection or may collect a different set than expected. The JVM chooses timing and strategy.
Why Other Options Are Wrong:
There is no x.delete()
in Java; finalize()
is not a destructor and calling it manually is incorrect; Runtime.getRuntime().gc()
is merely a hint; claims of immediate destruction are false.
Common Pitfalls:
Assuming GC is deterministic; relying on finalize()
for resource management instead of try-with-resources/close.
Final Answer:
Only the garbage collection system can destroy an object.
Discussion & Comments