Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Quiz 16: Eligible Objects for Garbage Collection

DZone's Guide to

Java Quiz 16: Eligible Objects for Garbage Collection

Check out the answer to the previous Java quiz about encapsulation before trying your hand at the ins and outs of garbage collection.

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

Before we start with this week's puzzle, here is the answer to Java Quiz 15: Improve Encapsulation of Your Code.

Adding and removing elements from the list can be prevented by returning a copy of the list as follows.

Replace the statement return customers;  with return new ArrayList(customers);.

You can also return a clone of the ArrayList as follows:

return (ArrayList<String>) customers.clone();


Note: This Java quiz series demonstrates ideas and tricks. The answers that are presented here might not be the best solutions in every case. Some members also suggested other ideas in the comments, and a memeber has shared this puzzle on Reddit. You might consider joining those discussions for more information. 

Here is the Java puzzle for today!

Consider the following code snippet:

  1. After which line of code is the car object created on line 1 eligible for garbage collection?

  2. Is there a way to prove that your answer is correct?

public class CarTest
{
    private Car c;
   
    void myMethod(Car car)
    {
        c = car;
    }
    public static void main(String[] args)
    {
        Car car = new Car("BMW"); // 1
        CarTest ct = new CarTest(); // 2
        ct.myMethod(car); // 3
        Car car2 = car; // 4
        car = new Car("Tesla"); // 5
        car = null; // 6
        car2 = null; // 7
        ct = new CarTest(); // 8
    }
}
class Car
{
    String brand;
   
    Car(String brand)
    {
        this.brand = brand;
    }
}


The correct answer and its explanation will be included in the next quiz in two weeks! For more Java quizzes, puzzles, and assignments, take a look at my site!

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
java ,quiz ,garbage collection ,encapsulation

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}