comander derp
comander derp

Reputation: 63

How to destroy an object in java without a name?

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

Answers (4)

Andrew
Andrew

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.

enter image description here

Upvotes: 4

Rasulbek Abdurasulov
Rasulbek Abdurasulov

Reputation: 111

Java will automatically delete them, it is called Garbage Collecting ;-)

Upvotes: 1

nbirla
nbirla

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

Praveen Kumar
Praveen Kumar

Reputation: 1539

If the object is a local variable it will automatically get garbage collected when ever the garbage collection occurs.

Upvotes: 0

Related Questions