Interview question: Objects eligible for garbage collection

前端 未结 7 865
无人共我
无人共我 2020-12-02 19:03

Give the following code:

class A {
    Boolean b;
    A easyMethod(A a){
        a = null;
        return a;
    }
    public static void main(String [] args         


        
相关标签:
7条回答
  • 2020-12-02 20:02

    Provided a1.go(a2) is actually meant to be a1.easyMethod(a2), the answer is indeed 2, but not the ones you listed. As Bozho rightly pointed out, b is not initialized, so it doesn't refer to any object. The two objects eligible for garbage collection at the point of the comment are the ones originally referenced by a1 and a3.

    a1 is obviously nulled out, and a3 is reassigned to the return value of a1.easyMethod(a2), which is null. However, a2 is not affected by the method call, as Java is pass by value, so only a copy of the reference a2 is passed to the method. Even though the copy is set to null, that does not affect the value of the original a2.

    0 讨论(0)
提交回复
热议问题