Will the car_object_1 be able to garbage collected? Somebody maintain that as car_object_1 has two reference so it will never be garaged collected. Is it true?
Car createACar()
{
Car c = new MyCar(); //car_object_1 was created
return c;
}
void use_the_car()
{
Car c2 = createACar();
c2.run();
}
No, they’re talking nonsense. Assuming there’s nothing within
run()which stashes a reference somewhere, the car is eligible for garbage collection after thec2.run();statement inuse_the_car.Java is not reference counted – even circular references aren’t a problem (e.g. where a
Carand aDriverhave a reference to each other, but nothing has a reference to either of them).Perhaps the person you were talking to was thinking of a slightly different situation?