2

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?
2
  • 4
    In Java, unlike C/C++, the JVM handles garbage collection for you. You don't need to call delete or anything like that. Commented Jun 30, 2016 at 6:22
  • 2
    You should review a basic tutorial of how Java works. Commented Jun 30, 2016 at 6:23

4 Answers 4

4
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

Sign up to request clarification or add additional context in comments.

2 Comments

There is no such thing in java. In Java garbage collection is automated we do not have control over it.
We cannot force the JVM to garbage collect (not without a massive hack), but we can politely ask it to using System.gc().
1

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.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.