aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes 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 "Garbage Collection" Watch "Garbage Collection" New topic
Author

Garbage Collection

Vidya Singh
Greenhorn

Joined: Mar 21, 2007
Posts: 28
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

Joined: May 08, 2008
Posts: 1
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

Joined: May 31, 2007
Posts: 42
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

Joined: Mar 22, 2008
Posts: 265

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 ]

There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14350
    
  22

Please do not enclose your whole post in [ code ] ... [ /code ] tags.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8883
    
    5
as always - the real exam never uses String objects in GC related questions!


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Garbage Collection