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

janne s
Ranch Hand

Joined: Sep 21, 2004
Posts: 81
Hi! Folks

Local variables in methods go out of scope when the method exits. At this point the methods are eligible for garbage collection. Each time the method comes into scope the local variables are re-created.

i've doubts:

1. In the above statement what does methods are eligible for garbage collection mean?


2. Does variables in method r candidates/eligible for gc??? yes, i know..once method exits variables go out of scope...but variables r not garbage collected.


i'm confused...


class A
{

String s;

A(String s) { this.s =s;}

public void finalize() { System.out.println(s);}

}


public class BDemo

{
double d;

public void static m1()
{

A a1 = new A("hello"); // 1

String s = new String("destroy"); //2


int j= 10; //3
String s = "s1"; //4
String s2 = "s2"; //5
String s2=s;

}

public static void main(String args[])
{

BDemo.m1(); System.gc();

}
}


In the above program when the method exits the variables 'n'objects created in the method go out of scope. Therefore "hello" 'n' "destroy" are eligible for gc as they r objects. What about j,s,s2 ??? R they candidates for gc.


Thank you in advance.
jaya
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
First of all, a method is never garbage collected. You only GC objects and those are only GC'd when there is no longer a reference to them from an active part of the application.

So, let's say we have a local variable, like this:



When that method terminates, sb will be out of scope and the object referenced by sb will be eligible for garbage collection. What happens to sb? Well sb is just a reference variable - it just vanishes into thin air. It's gone...forever.

Same thing goes for pimitives. They're not objects so they're not garbage collected. Only objects are garbage collected.

I hope that helps.


SCJP Tipline, etc.
janne s
Ranch Hand

Joined: Sep 21, 2004
Posts: 81
Hi! Corey

Thank you

jaya
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Garbage Collection
 
Similar Threads
objects eligible for GC?
GARBAGE COLLECTION (HFJ PG 266 )
new object in method
few doubts
Help with Garbage Collection