File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes how many objects  Eligible for 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 "how many objects  Eligible for garbage collection" Watch "how many objects  Eligible for garbage collection" New topic

how many objects Eligible for garbage collection

sameer kumar

Joined: Mar 22, 2004
Posts: 13
public void countDown(){
String s = null;
for (int i=3; i>=0; i--){
s = String.valueOf(i); //line x
System.out.println("Done"); //line y
at //liney how many object available for garbage collection
answer is given 2.
but i think 3
how's 2 can any body tell me
thanx in advance
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
I would have to agree:
4 Strings are created: "4", "3", "2", "1".
At line "y", "1" is held in the variable s, so it is not eligible for garbage collection, but the other 3 are. So, you are correct (if you've correctly copied the question).

Sriram Vadlamani

Joined: Feb 10, 2004
Posts: 9
From the given code:
String.ValueOf returns value of type String, so objects are created.
From the iteration there will be four string objects created (3,2,1,0) of which s will hold the value of 0 and the rest of them are eligible for garbage collection. That gives 3 objects eligible for Garbage Collection at line y
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Welcome to Javaranch
We'd like you to read the Javaranch Naming Policy and change your publicly displayed name (change it here) to comply with our unique rule. Thank you.

SCJP Tipline, etc.
I agree. Here's the link:
subject: how many objects Eligible for garbage collection
It's not a secret anymore!