0

Will reassigning a reference variable to null before reassigning it to a new object releases the old memory which it used to hold or is it the work of Garbage Collector?

Dog obj = new Dog("d1");
if(obj!=null)
    obj = null; // will this release the memory?
obj = new Dog("d2");

OR

Dog obj = new Dog("d1");
obj = new Dog("d2");
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 1
    The work of Garbage Collector. – Ismail Oct 07 '20 at 09:00
  • 1
    Assigning `null` does completily nothing. – Amongalen Oct 07 '20 at 09:00
  • Assigning null first could be useful in the very specific circumstance where you need to let the old object be gc _before_ you create the new object. For instance, if the objects are very big and you're working with very limited memory. – khelwood Oct 07 '20 at 09:05

2 Answers2

2

No, it is not compulsory and does in fact not do anything useful.

Assigning null to a variable never on its own releases memory. At most it removes one reference that keeps an object reachable and if it was the last reference, then the object can eventually become garbage collected.

But assigning any other reference to that variable does the same thing (i.e. remove the reference to the original object), so assigning null to it before reassigning it is an unnecessary step.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
1

You do not have to do this! The garbage collector will reclaim the memory either way.

i.e. the following is sufficient:

Dog obj = new Dog("d1");
obj = new Dog("d2");
Matthew
  • 10,361
  • 5
  • 42
  • 54