In my Java book there is an exercise that ask you to : “Allocate 10000 Rational objects without saving them in variables to they become garbage.”
Is below the correct way to allocate objects without assigning them to varaibles?
for (int i = 0; i < 10000; i++) {
new Rational();
}
Thanks
That’s correct, each
Rationalis instantiated without a reference and therefore are subsequently garbage collected at some point. Java doesn’t have a way to force garbage collection, but you can callRuntime.gc()to request a garbage collection.