Why is the indicated object entitled to garbage collection?

For the record, I am NOT a Java newbie, but rather a mid-level guy who has forgotten a bit about the basics of Java.

class C {
    public static void main (String a []) {
        C c1 = new C ();
        C c2 = m1 (c1); // line 4
        C c3 = new C ();
        c2 = c3; // line 6
        anothermethod ();
    }
    static C m1 (C ob1) {
        ob1 = new C (); // line 10
        return ob1;
    }
    void anothermethod () {}
}

From the code above:

  • Why, after line 6, are 2 type objects available Cfor garbage collection (GC)?

  • , 4 10, c1 m1(). , 6, 1 ( 2), GC. , java pass-by-value, pass-by-reference?

+3
2

, GC 6 C? (c2). , ?

c1 m1: , ( ), - , , - . , m1, , - , , ( c1, - main).

+1

pass-reference-by-value pass-values-by-reference:)

Java Pass By Reference
Java

, #, " ": p/a:
, " " .

, , :

c1 = new C("Alice");
    // m1(C obj1) {     -- c1 gets passed to m1, a copy of the reference is made.
    //                  -- there are now two references to Alice (c1, obj1)
    //    obj1 = new C("Bob"); -- there is now one reference to Alice
                                // and one reference to Bob
    //    return obj1;  -- returns a reference to Bob(c1 still reference Alice)
    // }                -- when m1 returns, one of the references to Alice disappears.
c2 = m1(c1); // c2 points to Bob 
c3 = new C("Charlie");
c2 = c3;      // <-- Bob is eligible for collection. 
              // There are now two references to Charlie
+4

Source: https://habr.com/ru/post/1733552/


All Articles