• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how many objects Eligible for garbage collection

 
sameer kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Samikumar,
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic