Take a look at the following code
for(int i = 0; i < 10; i++) {
new Object();
}
Will the Garbage Collector kick in every iteration, since there is no reference to the object? Is it usually discouraged to create objects in iterations without any reference?
Probably not. It’s not like JVMs are generally reference counted as such. A small amount of garbage will be created – each object will be eligible for collection after the iteration, but when those objects are actually collected isn’t specified.
It’s normally not a good idea to create objects for no purpose whatsoever. I’m not sure what you mean by “without any reference”. If you’ve got a reason to create a fresh object in each iteration, and there’s no need for it after the iteration has completed, that’s fine.