Java MCQ: Which method is called by the garbage collector in Java?
a) dispose()
b) finalize()
c) destructor()
d) delete()
Answer:
b) finalize()
Explanation:
In Java, the finalize()
method is called by the garbage collector just before an object is destroyed. This method provides an opportunity for the object to clean up resources, such as closing files or releasing memory, before it is removed from memory.
However, the use of finalize()
is generally discouraged because it is unpredictable and can lead to performance issues. With the introduction of try-with-resources and other resource management techniques, the need for finalize()
has diminished.
Understanding how garbage collection works and the limitations of finalize()
is important for efficient Java memory management.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html