This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes GC - Bill Brodgen Exam Cram Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "GC - Bill Brodgen Exam Cram" Watch "GC - Bill Brodgen Exam Cram" New topic

GC - Bill Brodgen Exam Cram

Shah Chunky
Ranch Hand

Joined: Dec 27, 2000
Posts: 116

Hello all
Can someone tell me when will the String object created will be Garbage
1 class Test
2 {
3 public static void main(String[] args)
4 {
5 String str = new String("Hello");
6 System.out.println(str);
7 }
8 }
I think after Line 6, It will be GC.
Does someone have differrent Answer.
Also look at the below code :-
This is from Bill Brodgen's Exam Cram - pg 163
1 class Test
2 {
3 public static void main(String[] args)
4 {
5for (int i = 10;i>=0;i--)
7 String tmp = Integer.toString(i);
9 }
10 System.out.println("BOOM");
11 }
12 }
The Question asked is how many objects r GC after Line 10 ?
The Answer given was 10, & not 11 as it says that the local variable
still has a reference to the last String created.
What i don't understand is that in my first Example, if the object is
has no longer reference then it will be Eligible for GC which in the
example is at Line 6, i.e. after "System.out.println(str);"
So how come there is still a refernce in the Bill Brodgen's Example.

Shah Chunky - Sun Certified Java2 Programmer.
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
In your first example, the String will have a reference until the main method exits and will never be garbage collected because the program will end.
The example of my question (which has caused endless confusion and argument) turns out to be pretty tricky. Basically it was a bad way to make a question about GC. In fact, using String objects in GC questions causes nothing but trouble.
See the following for a discussion:
While at the lanw site, go to /books/errata
and get the total list of errata for the Exam Cram book.

author of:
Stevie Kaligis
Ranch Hand

Joined: Feb 04, 2001
Posts: 400
answer Q#1 :
After line 7, not after line 6.
answer Q#2 :
I think because Bill said "after line 10", not "after line 11".
Hima Mangal
Ranch Hand

Joined: Feb 25, 2001
Posts: 82
hi all..
what i still don't understand is that how will be the no of variables eligible for GC be 10 and not 11 after line 10, since the tmp variable is local to the for loop and will be out of scope once the for loop ends..
pls help me out...


Hima<BR>Sun Certified Java Programmer
subject: GC - Bill Brodgen Exam Cram
It's not a secret anymore!