Reputation: 63
I am looping through an array and based on the values creating a different object. and I want to know how would you delete or de-reference an object with no name.
Here's an example of what I mean
new Test(); // so now how would I delete this instance of test?
Upvotes: 2
Views: 585
Reputation: 49606
new Test().m1().m2();
// here the previous instance may be deleted, there is no reference to `new Test()`
It will be deleted by the GC after (we don't know exactly when it will be called) all operations (m1
, m2
methods in our example) over it are done.
You could call Runtime.getRuntime().gc()
(or simply System.gc()
), but there is no guarantee that the garbage collector will come.
I tried to draw how I can imagine it.
Upvotes: 4
Reputation: 111
Java will automatically delete them, it is called Garbage Collecting ;-)
Upvotes: 1
Reputation: 610
Java performs GC by itself, no need to do it manually.
Mentioned Object should be not be in use to be eligible for GC. JVM will do multiple scans and will move these objects from one generation to another to determine the eligibility of GC and frees the memory when the objects are not reachable.
Upvotes: 1
Reputation: 1539
If the object is a local variable it will automatically get garbage collected when ever the garbage collection occurs.
Upvotes: 0