For the record, I'm NOT a Java Beginner, but -- rather - an intermediate-level guy who kinda forgot a bit about fundamentals about 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 above code:
Why is it that after line 6, 2 objects of type C
are eligible for Garbage Collection(GC)?
Why isn't it that in line 4 and line 10, a copy of c1
is passed into the m1()
method. So, eventually in line 6, there is going to be 1 Object (not 2) that are going to be eligible for GC. After all, isn't java pass -by-value rather than pass-by-reference?
What makes you think two objects of type C
are available for GC after line 6? I only see one (c2
). What tool are you using that tells you otherwise?
Regarding your question about passing c1
into your m1
method: What you pass (by value) is a reference to the object -- a handle by which you can grab the object, if you will -- not a copy of it. The fact you pass a reference into m1
is completely irrelevant, in fact -- you never use that reference, you immediately overwrite it with a reference to a new object, which you then return (this does not affect the c1
that is still referenced in main
).