Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Again on GC( JQ++)

 
swapna sivaraju
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please help!!!
How many objects are eligible for garbage collection when the control reaches line 4 if the method process() is called with the argument of 5?

1. public void process(int count)
{
2. for ( int i = 1; i < count; i++ )
{
3. Object temp = " Hello "+i;
}
4.
}

Ans is 0 as--
All the String objects are interned ie. Java caches all the string objects (except which are created by doing new)

Is this because in the above code " Hello "+i
is creating a string literal object (not a string object on heap )using constant expression so that's why the Garbage collection doesnot take place???
And if the statement would have been like
{
String str=new String("Hello");
Object o=str+i;
}
then would the answer be 4??
swapna
 
swapna sivaraju
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Valentin
Whatever i could get from those discussions is
that temp is not a String literal as in the concatenation there is one String literal and other is a variable whose value is not known at
compile time so this is computed at runtime thus
making the temp as a String object.
Am i right now??? let me know..
swapna.
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!