answersLogoWhite

0

AMIT KUMAR

  • 3th Nov , 2014
Java does not support destructors, since java supports the concept of garbage collection,hence the garbage collector is used to automatically free the space which has occupied by the program while running.Garbage collector calls the finalize() method which is defined in the object class. finalize() method is called once for each object.
User Avatar

Wiki User

9y ago

Still curious? Ask our experts.

Chat with our AI personalities

RossRoss
Every question is just a happy little opportunity.
Chat with Ross
ProfessorProfessor
I will give you the most educated answer.
Chat with Professor
FranFran
I've made my fair share of mistakes, and if I can help you avoid a few, I'd sure like to try.
Chat with Fran
More answers

The finalize() method in Java is the closest mechanism to the concept of a destructor. But since the garbage collector is not guaranteed to run at any specific time depending on finalize() to cleanup resources is not best practice.

The finalize() method in java objects is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Best practice in Java is to close resources and release references to them when they are no longer needed so the garbage collector can reclaim memory. So for example, InputStreams have a close() method which should be called in a finally block to ensure the streams are closed.

Java 1.7 introduced the try-with-resources statement that declares one or more resources and closes the resource after the statement block is executed even if an exception occurs. This a destructor-like mechanism but must be explicitly called in the program.

User Avatar

Wiki User

12y ago
User Avatar

The purpose of a Destructor is usually to clear off unused variables and clean up the memory. Java has in built memory handling mechanisms (Garbage collection) that clear off unused memory automatically. Hence there is no requirement for destructor methods.

Tip: In spite of automatic garbage collection by java, it is a good practice to nullify all unused objects in the finally block of the code.

User Avatar

Wiki User

16y ago
User Avatar

Add your answer:

Earn +20 pts
Q: Why java does not support destructor?
Write your answer...
Submit
Still have questions?
magnify glass
imp