• Post Reply Bookmark Topic Watch Topic
  • New Topic

Assigning null to Complex Type object in the context of memory in java  RSS feed

 
Sagar Singh B
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the meaning of assigning null to Complex Type object in the context of memory in java language.
Eg

while(true) //Approx 9000 times
{

Employee objEmployee = new Employee ();

objEmployee = //Put some value

objEmployee = null;
}

Does assigning null to the complex type make the object ready for garbage collection in java.Also
is it the way to efficient memory management in java.

Regards,
Sagar.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the example you give, it has no effect at all.

The variable is declared in the scope of the loop, at each iteration the variable will go out-of-scope which means the Employee object will already be eligible for garbage collection (if there's nothing else referencing the object). Setting a variable to null does not give the garbage collector a "sign" or do anything else to tip the garbage collector that the object is ready to be garbage collected (some people seem to think this).

Ofcourse, setting a variable to null can make an object eligible for garbage collection, if that variable was the only thing referring to the object. But you should only do this when you understand what you're doing and why. I've seen people setting variables to null with a kind of superstitious belief that this somehow makes the program more memory-efficient; don't become one of those people...

Also, you should be aware that variables are not objects, but only references to objects. You don't "assign null to a complex type object"; you can set a variable to null, which means that it doesn't refer to any object anymore.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It allows the object to lose one reference, thereby allowing it to be garbage collected if it was the last one. For local variables it's mostly unnecessary though, unless you have a lot of code afterwards. In your example for instance the variable goes out of scope immediately after the assignment of null so the reference would be dropped anyway.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!