-3
public class GarbageCollection {
    public static void main(String[] args) 
    {
        GarbageCollection gb= new GarbageCollection();
        GarbageCollection gb2=method1(gb);
        GarbageCollection gb4=new GarbageCollection();
        gb2=gb4;/*line 4*/
        somethinsgsillogical();
    }

    static void somethinsgsillogical() {
     // TODO Auto-generated method stub

    }

    static GarbageCollection method1(GarbageCollection mgb)
    {
        mgb=new GarbageCollection();
        return mgb;
    }
}

Is the program logical? If yes kindly sate that After line 4, how many objects are eligible for garbage collection

John
  • 3,769
  • 6
  • 30
  • 49

1 Answers1

1

This seems like a homework question and all you have done is pretty much just post the question so I'll give you a hint:

gb2=gb4

is going to make whatever gb2 was assigned to eligible for garbage collection. This object is garbage because it isn't being referenced any more. When garbage isn't cleaned up, or marked for garbage collection, we get memory leaks.

It is actually pretty hard to leak memory in Java because of the fact that Java has a garbage collector, but leaks do still happen when memory isn't managed properly. Always set objects to null when you are done using them:

gb2 = null;
gb4 = null;

When an object has no more references to it, the garbage collector will consider it for garbage collection.

For more info on garbage collection, there is a really good page on SO for it. I really recommend reading it:

Community
  • 1
  • 1
John
  • 3,769
  • 6
  • 30
  • 49
  • *`gb2=gb4` is going to make whatever gb2 was assigned to eligible for garbage collection.* That may be true in this case but note that *`a=b` makes whatever `a` was assigned to eligible for garbage collection* is not true in the general case, as something else could still be holding that reference. – Jason C Apr 20 '14 at 05:50
  • @JasonC I was giving a specific answer to this question, see my final quote: `When an object has no more references to it, the garbage collector will consider it for garbage collection.` – John Apr 20 '14 at 05:55
  • 1
    I know. My comment was directed more towards the OP. – Jason C Apr 20 '14 at 06:01
  • @JasonC oh sorry, I was misinterpreting the context of your response. – John Apr 20 '14 at 06:02
  • Hi John(and John C),it was the first program I posted in Stackoverflow. – user3231140 Apr 21 '14 at 21:19
  • Sorry,Novice in Stackoverflow.That means only gb2 (object reference) is eligible for garbage collection but what about gb4 (object reference),as it has an object of which it is a reference. Conceptually what is the internal workflow of gc. Why the other object gb not eligible for garbage collection,is it bcoz its is already had been referenced but it is the same case with gb4. Is it right to tell these gb/gb1/gb2 objects(as they are actually reference)? – user3231140 Apr 21 '14 at 21:56