Reputation: 2037
In some languages like Python
, there are ways by we can "delete" an object from the heap explicitly. As for example:
s = "This is a Test"
del s
Now, the object s
cannot be used anymore. Now, my question is, can we do anything similar in Java
? Yes, I know it is garbage collected, and that is a huge advantage in most situations, but what if I want to manually delete an object? By the way, does del
in Python actually delete the object, or does it delete the reference variable? Thanks in advance for any help!
Upvotes: 2
Views: 226
Reputation: 360
The object will get deleted from heap once it goes out of scope. You can enclose s
in the minimal possible scope where it is used. i.e. either enclose within a block of {} braces, or define a separate method where it is used
Upvotes: 1
Reputation: 13854
As Luiggi Mendoza has said you can not manually delete.How ever you can refer it to NULL
.
To free the memory you can call System.gc()
.But there is no guarantee that memory will be freed.
Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
Upvotes: 0
Reputation: 136102
In general you need to null all references to the object after which the object cannot be used anymore and will be deleted on next GC. But string constants objects like "This is a Test" are stored in a pool and are not deleted if even there is no reference to them.
Upvotes: 1
Reputation: 775
in java for sure we cannot delete the object...but we can try with System.gc(); or if we want to lost the reference of a object we can set the value of object reference null; .. but after setting null value we can't access the object but it still remains in memory......
Upvotes: 1
Reputation: 85789
can we do anything similar in Java?
No.
At most you can nullify the object:
s = null;
This will mark the object for garbage collection, and when trying to use it (except when assigning a new value to it), you will get a NullPointerException
.
s = null;
...
s.foo(); //this will throw a NullPointerException
Upvotes: 1