• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method to set objects to null  RSS feed

 
Fred Victa
Ranch Hand
Posts: 206
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an application that creates objects in various methods. What is your opinion of creating a method that would be called by other methods in order to set the method's objects to null?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) You can't.
2) What's the point over simply setting the variable to null yourself?
3) Why?
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the objects were assigned to a local variable in the first method then nothing the second method does will be able to affect the reference value held in that local variable.

This is because java uses pass-by-value semantics when calling methods.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, you cannot set objects to null. You can set variables to null. It's important to understand the difference between objects and variables. A variable* is a reference to an object - you can set it to the special value null which means that the variable is not pointing to an object.

There's almost never a good reason to manually set variables to null. You do not normally need to set variables to null to let the garbage collector free up the memory used by those objects.

So, you don't need a general-purpose method to clean up objects. Let the garbage collector do its job, don't clutter up your own program with unnecessary code that tries to help the garbage collector.

* of a non-primitive type
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ignoring primitives for now...

variable are like address cards. They hold the address to a house or building. If you pass a variable into a method, you can think of it as making a copy of the address card and handing that to the method. If you erase that 2nd card's contents, the first card still has its copy, and nothing changes on the actual building.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!