File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Assign null to unneeded object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Assign null to unneeded object" Watch "Assign null to unneeded object" New topic

Assign null to unneeded object

Samuel Huang

Joined: Oct 29, 2001
Posts: 8

To explicitly assign null to unneeded objects is a good or bad programming habit? Why?
Many thanks in advance!
Samuel Huang
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

Some people like to do it as they feel that it will be gc quicker. I never do it, it's a style thing.

Please ignore post, I have no idea what I am talking about.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Whenever you have a reference to an object stored in a variable, that object cannot be garbage-collected.
If your reference is in a local variable in a short-duration method, it will go out of scope quickly and be available for garbage collection. Therefore, no need to set reference to null. In this case, setting it to null is a style thing, as the previous posting suggested. I think it's good practice, but can't claim that I actually always do it!
If the variable containing your reference is potentially long-lived (member data of long-lived object or, worse, class static data), then garbage collection could be prevented for a long time or for ever. In such cases, you should set references to null when they are no longer needed, to facilitate garbage collection.
In the worst case, failure to do this can result in a "memory leak".
Extra care has to be taken with arrays and collections. If an array or collection holds a reference to an object, that will prevent garbage collection. Long-lived arrays or collections could therefore cause memory leaks if not used carefully.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Samuel Huang

Joined: Oct 29, 2001
Posts: 8
Hi Christopher and Peter,
Thank you for your opinions, really useful.
I agree. Here's the link:
subject: Assign null to unneeded object
It's not a secret anymore!