Java puzzle 30: Simple garbage collection

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

Try to use the following principle to solve this puzzle!

When there is no references pointing to an object, that object can be eligible for garbage collection.

Java puzzle 30: Simple garbage collection

Level: Normal

Question: After which line number, the object bird created at line //1 is eligible for garbage collection?

public class TestBird
{
  public static void main(String[] args)
  {
    Bird bird = new Bird("Eagle"); // 1
    Bird bird2 = new Bird("Falcon"); // 2
    bird2 = bird; // 3
    bird = null; // 4
    Bird bird3 = bird; // 5
    bird2 = null; // 6
  }
}
class Bird
{
  String name;
  
  Bird(String name)
  {
    this.name = name;
  }
}
Author: Sar Maroof

For the answer and the explanation you can join the discussion below!

Some members thought that it should be line 4. That is understandable, but I already posted the explanation with the arguments why it should be after line 6. See the comments below!





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

6 Comments

Add a Comment
  1. Answer explanation

    bird2 at line 2 is also pointed to the same object bird at line 1.
    At line 4 the object bird points to null, but remember that the object bird 2 is still points to the object bird at line 1.
    After the statement bird2 = null; at line 6, there is no object points to the object bird at line 1.
    The object on line 1 is now eligible for garbage collection.

  2. Thanks for this nice post, I am not familiar with Garbage collection, but the way you demonstrate it is really interesting!

    1. You are welcome!

  3. I really don’t get it. I thought after line 4. Can anyone explain me why line 6?

      1. I try to give you a hint! Is there any reference pointing to the object bird after line 4? If you can answer this question, you can simply solve the puzzle.

Leave a Reply

Your email address will not be published. Required fields are marked *