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

Garbage Collection

 
sandhi mridul
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not getting this question.



According to me it should be after line 9 but the answer is after line 11.

Please explain me if the answer is right then why after line 11.

Thanks
Sandhya
 
Jeff Rummings
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at line 7:



The string is still reachable through the locObj reference. Line 11 is correct because all objects become unreachable beyond the if statement.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This example is a little tricky because the object is a String literal. See Strings, Literally for an explanation.

(My understanding is that garbage collection questions on the real exam will not involve String literals.)
 
Sheryl Pinto
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sandhi,

There is only one String object and that is "sample". anObj is just a reference pointing to "sample".

After line 7, both anObj and locObj point to "sample".
After line 9, reference anObj points to null but locObj is still pointing to "sample" and thus "sample" is not eligible for GC.

Also see:
http://faq.javaranch.com/java/ScjpFaq#stringLiteralGC

Sheryl.
 
sandhi mridul
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Arman I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic