Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Refference variables and garbage collection

 
Gjorgi Var
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
If we have two refference variables that are assigned to each other, both will reffer to the same object on the heap. But if we assign one of them to null after we have assigned it to the other variable, wll that object be subjected to garbage collection? Why would it be or would be not?
 
Tom Henner
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java passes a copy of the reference value. So setting a to null does not change the reference that b already has. Your object is safe from the gc.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the object is not available for garbage collection until there are NO MORE references to it. This is a very key concept since it is easy to forget to null out all references when you are finished with an object.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic