Reputation: 1035
How can I delete object manually in Java? Is there any method like obj.delete()
or obj.kill()
Upvotes: 2
Views: 3236
Reputation: 13539
There is no way to delete an object. Java's Garbage Collector will do it automatically when an object has no more references.
You can however run the Garbage Collector once you have removed all references to an object by calling System.gc(). Please do read the method's documentation carefully. It only guarantees best-effort to delete all objects marked for deletion.
You should also go through these discussions
Upvotes: 3
Reputation: 10349
There is no real way. Java has a special Garbage Collector which does that for you. Once your object doesn't have any references to it, it will be picked up by the Garbage Collector at some point and destroyed.
From Learning Java Tutorials:
The Garbage Collector
An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.
Upvotes: 10
Reputation: 24375
One of the main reasons for Java being so popular is the Garbage Collection. You do not have to worry about allocating or deallocating memory. That being said if you want to get rid of an object just set all references to the object to null and once the garbage collector runs the object will be disposed of.
You do have to worry about closing resources such as files, sockets, database connections etc... and for that you should do it in a try/finally block.
Upvotes: 2
Reputation: 15433
just assign the null value to it.
Let GC take care of this
obj = null;
Upvotes: -1