Salman
Salman

Reputation: 1264

Objects assignment and GC behavior in Java

Given code below. What is the final value of the object objectOfA_In_B ?

Class A 
{
    // Some parameters and method with complicated logic goes here
}


Class B
{
    A objectOfA_In_B = new A();

    B()
    {
     // Operation done on objectOfA
    }

    public A getObjectA()
    {
        return objectOfA_In_B;
    }   
}


Class C
{
    public static void main(String[] args)
    {
        try
        {
            A objectOfA_In_C = null;
            B objectOfB = new B();

            objectOfA_In_C = B.getObjectA()

            // Rest of logic goes here
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            objectOfA_In_C = null;
        }
    }
}

Question is: Will objectOfA_In_B be null as well by setting objectOfA_In_C to null in finally block of C's main method simply because they are pointting to the same object ? Are both objectOfA_In_C and objectOfA_In_B are ready to get collected from Garbage Collector ?

Upvotes: 0

Views: 65

Answers (3)

TheLostMind
TheLostMind

Reputation: 36304

Will objectOfA_In_B be null as well by setting objectOfA_In_C to null in finally block of C's main method simply because they are pointting to the same object ?

No, Java is pass by value. Even references to objects are passed by value. So, by setting objectOfA_In_C to null, objectOfA_In_B wont become null.

Are both objectOfA_In_C and objectOfA_In_B are ready to get collected from Garbage Collector

There is only one instance of A in question here and 2 references pointing to it (one of which is set to null in the finally block). That instance will be ready for GC when there will be no references pointing to it.Note that objectOfA_In_B still points to that instance.

Upvotes: 1

Clayn
Clayn

Reputation: 1036

It won't be nullsince you assign null just to the local reference. That won't change any reference that may point to that object. So objectOf_A_In_Bis not affected and therefore not ready to be collected by the GC

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41686

There are two variables here and only one object. Either of the variables can point to the object or not. An assignment to a variable has no effect on other variables. The object (not the variables) is ready for garbage collection when no variable points to it. Variables cannot be garbage collected, only objects can.

(Since this looks like homework, I left some conclusions to be made by you, since you want to learn. :))

Upvotes: 1

Related Questions