javamemory-managementjava-memory-leaks

What will happen If I initialize a Class object which is already initialized in JAVA?


I want to know what will happen if I initialize an already initialized Class object in Java. Does the garbage collector destroys the object and free the memory?.

Example code:

........
Object target = new MyClass();//First intialization
........
target = new MyClass();//Re-intialization //I want to know what will happen here
........

Solution

  • Object target = new MyClass();
    

    This will create a new object of MyClass() and target variable will refer to this object.

    After the second statement:

    target = new MyClass();
    

    Another new Object will be created and target will now refer to this newly created object. The previous object will have no reference and GC will free that memory.