Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Method to set objects to null  RSS feed

 
Ranch Hand
Posts: 208
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?
 
Author and ninkuma
Marshal
Posts: 66540
160
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?
 
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.
 
Java Cowboy
Sheriff
Posts: 16083
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
 
lowercase baba
Bartender
Posts: 12613
50
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.

 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!