What do I do if I want to reinitialize obj? That is, delete the existing object and create a new one which has a name obj.
public void checkInitialize()
{
X obj = new X();
}
Every time I invoke method checkInitialize(), I should reinitialize the object.
The short answer is that you have answered your own question with your code, -- if you create a new instance of a class with
X obj = new X();, then the object that was previously created and pointed to by reference
obj is no longer reachable and the JVM will eventually reclaim the space, -- there is no need to explicitely delete it, as garbage collection is automatic in
Java.
The long answer is that it's easy to introduce a memory leak in Java, despite of its automatic garbage collector. For example, suppose you created a new instance of
X and added it to a list (or any other container). Or perhaps you passed it to some method, and some other object
Y now holds a reference to
X. Now, if you make a new instance of
X and use the same reference
obj, the old object will
not be garbage collected, since it would still be reachable through the container or object
Y (assuming that the life time of
Y or the container is longer than that of
obj.
Hope that wasn't too complicated, -- perhaps someone else can explain this important concept better.