class C { public static void main(String a[]) { C c1=new C(); C c2=m1(c1); C c3=new C(); c2=c3; //6 anothermethod(); } static C m1(C ob1){ ob1 =new C(); return ob1; } } After line 6, how many objects are eligible for garbage collection?

  1. 1

  2. 2

  3. 3

  4. 4

  5. None of the above


Correct Option: B

AI Explanation

To determine the number of objects eligible for garbage collection after line 6, we need to analyze the code.

Let's break down the code and track the objects:

  1. C c1 = new C(); - This creates an object c1.
  2. C c2 = m1(c1); - This invokes the method m1 with c1 as a parameter. Inside the method, a new object ob1 is created and returned. This new object is assigned to c2. So, we have two objects c1 and ob1.
  3. C c3 = new C(); - This creates a new object c3.
  4. c2 = c3; - This assigns the object c3 to c2. Now, c2 refers to c3, and the object previously referred to by c2 (which was ob1) becomes eligible for garbage collection.
  5. anothermethod(); - This method call doesn't affect object eligibility for garbage collection.

After line 6, we have two objects (c1 and c3) that are still referenced, and one object (ob1) that is eligible for garbage collection since it is no longer referenced.

Therefore, the correct answer is B) 2 objects.

Find more quizzes: