Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection

 
Vidya Singh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Src:http://devesh2k1.googlepages.com/home

How many objects will be eligible for GC just after the method returns?
public void compute(Object p)
{
Object a = new Object();
int x = 100;
String str = "abc";
}
Answer: 1
Explanation: Objects passed to the method are never garbage collected in (or right after) that method. So p cannot be GCed. x is not an object. "abc" is a string literal which goes to the string pool and is not GCed. So, only a is eligible for GC.
-----------

what about the String. Str is also garbage collected, so answer should be 2.
[ May 09, 2008: Message edited by: Jesper Young ]
 
Alpa J Dedhia
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are not creating an object of the String. You are just creating a reference.

An object is created only when you type something as 'new'
 
Avi Sridhar
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Alpa J Dedhia:
You are not creating an object of the String. You are just creating a reference.

An object is created only when you type something as 'new'


When you say something like

String s = "helloworld";

it creates a new string object with value "helloworld" and assigns s to it.

So the answer should be 2 .

Correct me
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avi,

Alpa is correct. String str is just a reference, not an object. It's assigned a String literal out of the String Pool; a new String object isn't created that can be GC'ed.

This article explains in greater detail. The key point from this article is


String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection.

[ May 08, 2008: Message edited by: Stevi Deter ]
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15484
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please do not enclose your whole post in [ code ] ... [ /code ] tags.
 
Bert Bates
author
Sheriff
Posts: 8900
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as always - the real exam never uses String objects in GC related questions!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic