HKIT
HKIT

Reputation: 759

Array Garbage Collection in Java

I got 2 classes.

  1. ToyCar
  2. ToyShop

ToyShop has a toyCar field which accepts a ToyCar object.

public static void main(String[] args) {
  ToyCar[] cars = new ToyCar[3];
  cars[0] = new ToyCar();
  cars[1] = new ToyCar();
  cars[2] = new ToyCar();
  ToyShop company = new ToyShop();
  company.setToyCar(cars[2]);
  cars[0] = null;
  cars[1] = null;
  cars = null;
  print(company.getToyCar())
}

If I run the program, will the cars array be garbage collected, or just cars[0] and cars[1] is collected??

If the array is garbage collected, can I print out toyCar in company??

If my question does not make sense, please point out.

Upvotes: 0

Views: 694

Answers (2)

Stephen C
Stephen C

Reputation: 718778

Almost certainly, the program will complete before the GC runs. So ... technically ... nothing is garbage collected.

Similarly, when the main method finishes, all of the objects that it created will be unreachable and eligible to be garbage collected. (Even if the program didn't terminate.)

However, when you get to the print statement, the company object will be reachable and its toy field will be reachable, so the value of that field will be reachable ... and the ToyCar object it refers to won't have been garbage collected, whether or not the GC has run by then.

The general rule is that if your application can reach an object, it won't be garbage collected. Basically, don't worry about it. The object will still be there if your code can use it.

Upvotes: 2

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

Here these three lines of code construct three different new objects of ToyCar

  cars[0] = new ToyCar();
  cars[1] = new ToyCar();
  cars[2] = new ToyCar();

After execution of these two lines of code

cars[0] = null;
cars[1] = null;

first two car object will be eligible for garbage collection. because there is no external reference to that object exists in JVM.

Now Come to this line

ToyShop company = new ToyShop();
company.setToyCar(cars[2]);  //now car object at 2ond Index have external ref.

Here third Object reference is assigned to a reference Variable toyCar present as member variable in company.

So, After execution of line cars = null; there is still one external reference present in JVM.

So, Only 2 Object will eligible for garbage collection after execution of cars = null;.

Upvotes: 1

Related Questions