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

Garbage Collection

Vidya Singh

Joined: Mar 21, 2007
Posts: 28

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

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


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: 14957

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

Joined: Oct 14, 2002
Posts: 8898
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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Garbage Collection
It's not a secret anymore!