+ 2
Destructor in Java
Why there is no destructor in java in this tutorial
1 Réponse
+ 5
Java has a so called garbage collector. The garbage collector runs on the JVM (Java Virtual Machine) and gets rid of objects which are no longer in use.
The biggest benefit of Java garbage collection is that it automatically handles deletion of unused objects or objects that are out of reach to free up vital memory resources. In other languages like C++, the programmer needs to manage memory allocation which can be error prone, especially amongst beginners.
When an object has no references pointing to it or it goes out of scope, it becomes eligible for garbage collection (it gets removed from memory).
Here's an example:
#4 StringBuilder strB = new StringBuilder("test");
#5 strB = new StringBuilder("test2");
The object on line 4 is now eligible for garbage collection as it's got no references pointing to it. strB (which is a reference) is now pointing to a new StringBuilder object.