-1

Here is my code snippet where i am using a final object reference..

public class FinalTest{
    private int rollNo;
    public static void main(String[] args){
        final FinalTest obj = new FinalTest();
        obj.rollNo=20;

        obj.rollNo=30;

        System.out.println(obj.rollNo);
        obj = null; 

    }
}

and finally i am assigning null to the reference variable obj.. but java does not allow this. so i want to know in such case ( when we don't assign null to our object reference obj) when does this obj will become eligible for garbage collection.

Vijender Kumar
  • 1,285
  • 2
  • 17
  • 26

1 Answers1

3

The object, which obj holds reference to, should become eligible for garbage collection when the method completes, because the program flow should be already on a different execution scope (i.e. other method/class)

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • i got it. but now i have got one more doubt. what would happen if i create the object like this.. final static FinalTest obj = new FinalTest(). in this case i am creating this object as an instance variable. then when it will become eligible for garbage collection ? – Vijender Kumar Jan 18 '16 at 15:48
  • The "`obj` reference" is never garbage collected. It's a variable. The object to which it points becomes eligible when there are not further references to it. – Andy Thomas Jan 18 '16 at 15:50
  • @AndyThomas i understood what you said. but here the object is being pointed by the obj reference type which is final so that means this object will be engaged to obj forever as we can't set obj to null explicitly because it is being marked final. so in such case when would my object which is being pointed by obj will become eligible for garbage collection ? – Vijender Kumar Jan 18 '16 at 15:52
  • Your local variable `obj` goes out of scope at the end of its method. Its lifetime is shorter than forever. – Andy Thomas Jan 18 '16 at 15:59
  • @AndyThomas you are right. i understood what you said. but would you please tell me what would be the case if i declare the object like this:- final static FinalTest obj = new FinalTest();. here i have decared it as an instance variable. now when this object will be eligible for garbage collection. – Vijender Kumar Jan 18 '16 at 16:02
  • @VijendarThakur - To be more precise, that would declare a static field that contains a reference to a newly created object. (You'd need to move the line outside the method.) Static fields are *class variables* rather than instance variables. The field will live as long as the class, preventing collection of the object it references. More detail is in the existing question ["Are static fields open to garbage collection?"](http://stackoverflow.com/questions/453023/are-static-fields-open-for-garbage-collection). – Andy Thomas Jan 18 '16 at 16:37