Reputation: 759
I got 2 classes.
- ToyCar
- 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
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
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