My Java teacher (High school course) was talking about loops and she said that if you have a for loop like:
for (int i = 0; i < max; i++) {
//something
}
you can’t use the variable i outside of the loop because the garbage collection feature deletes it because it senses that it’s “unneeded” (I know about scopes and that this is BS because the same thing happens in all languages and C++ doesn’t even have garbage collection). Now the question is… What does Garbage Collection actually do? (I looked it up and it had something to do with heaps which I don’t know about yet so someone explain this to me)
Thanks
Correct. The variable
ican’t be used outside the loop because of scope — it has nothing to do with the GC (outside of potential object reach-ability).The Garbage Collector is responsible for reclaiming objects which are no longer strongly-reachable. A garbage collector has nothing [directly] to do with variables, although a variable can keep an object strongly-reachable. (Also, primitive values, such as
intare not objects are thus never dealt with by the GC 😉I would recommend reading through Chapter 9 of Inside the Java Virtual Machine:
Garbage Collection and The Truth About Garbage Collection as I believe they will provide sufficient answers/insight and justification. (The Garbage Collection wikipedia entry is also a good start and nicely summarizes GC in general.)
From “The Truth”:
Happy coding.