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

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!

encapsulation, garbage collection, java, quiz

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}