File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes q on garbage collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "q on garbage collection" Watch "q on garbage collection" New topic
Author

q on garbage collection

JayaSiji Gopal
Ranch Hand

Joined: Sep 27, 2004
Posts: 303
void method X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
} //4

when is s eligible for garbage collection?

Before statement labeled 1
Before statement labeled 2
Before statement labeled 3
Before statement labeled 4
Never

i answered never, but the correct answer is 'before statement labeled 4'.
I didnt understand yy?
is is bcos s = s + r and r = null. anything added to null is null?


SCJP 1.4, SCWCD 1.4<br /> <br />Thanks in advance!<br />Jayashree.
navneet shrivastava
Ranch Hand

Joined: Jul 09, 2004
Posts: 39
No, it is so bcoz 's' is a local variable (local to the method) so its scope is within the method. So, it wud be eligible for gc as soon as method ends.


+nav
Muralidhar Mandapati
Greenhorn

Joined: Nov 14, 2004
Posts: 23
Check the life of the variable. Since the variable s is a local variable , it does not exists outside the method and hence it should be eligible for garbage collection. Note that the question says it is eligle for garbage collection but not forcing the garbage collector to take the object.


Cheers,
Murali
Atul Chandran
Greenhorn

Joined: Oct 24, 2004
Posts: 22
s = s + r;
The above line will produce a new String literal "abcnull" and s will be referring to this new object. The String object "abc" referred to by s previously will be eligible for garbage collection.

Note in the question it is given as "Before statement 4" and local variables become eligible for garbage collection only after statement 4.
PNS Subramanian
Ranch Hand

Joined: Jul 13, 2004
Posts: 150
Agree with Atul's comment.
The question talks about the original object pointed to by s. Local variables are available for gc once the method ends - i.e NOT before line 4.
Please correct me if otherwise.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: q on garbage collection