1

I have a feeling this question will be obvious, but I think the questions should still be asked just to be safe.

If I have a class that accepts parameters, and I continuously call the same class with the same reference name, but different parameters, do I have to null out the previous class instance to prevent ram from getting eaten up with every new instance? for example

 RandomClass className = new RandomClass(argument1);
 while(className.classMethod() != null){
     className = new RandomClass(argument i)
     i++;
 }

I'm assuming The className with argument one would be destroyed when className with argument2 is called? or would I have to

 RandomClass className = new RandomClass(argument1);
 while(className.classMethod() != null){
     className = new RandomClass(argument i);
     className = null;
     i++;
 }

just to be safe?

gkrls
  • 2,618
  • 2
  • 15
  • 29
  • Google "Java garbage collection" – Robby Cornelissen Jul 27 '14 at 23:13
  • You do not have "class pointers", you have *references* to *objects*. The objects are *instances* of some class (eg, "RandomClass"), but this does not make them classes. And, as suggested, study up on "garbage collection" in Java. – Hot Licks Jul 27 '14 at 23:25
  • possible duplicate of [Does setting Java objects to null do anything anymore?](http://stackoverflow.com/questions/850878/does-setting-java-objects-to-null-do-anything-anymore) – Erwin Bolwidt Jul 28 '14 at 02:07

2 Answers2

3

Before entering the loop, you have

className --> 1234 // an identifier of the object for our purposes

After the loop has iterated one

className --> 9542 

The variable className is referencing a different object and now your program no longer holds a referenced to the object with identifier 1234. It will therefore be garbage collected eventually. You don't need to assign null to the variable. (There are some extremely rare cases where you would, but don't go looking for trouble with those yet.)

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
3

No need to null variables, new java and C#/C++ engines will take care of garbage collection and RAM would not be lost.

Rusty30
  • 171
  • 9
  • 1
    Not C. C is not garbage collected, and it can't be in general. (So-called conservative collectors for C rely on assumptions about the way that a program handles pointer values.) – Stephen C Jul 27 '14 at 23:20
  • you're right I meant recent C# C++ compilers. In the old days of C stack overflow was something that really happened :) – Rusty30 Jul 27 '14 at 23:21