I can't figure out an SCJP questions even after getting the right answer:
From the following code(source: http://scjptest.com), we need to determine when is object referenced as myInt be eligible for garbage collection:
01.public void doStuff() {
02. Integer arr[] = new Integer[5];
03. for (int i = 0; i < arr.length; i++) {
04. Integer myInt = new Integer(i);
05. arr[i] = myInt;
06. }
07. System.out.println("end");
08.}
The answer states that it is eligible for GC on line 6. But I think the object is simply not eligable for GC until after line 7. Because, the object being referenced as myInt is also referred to as arr[i] as well. So, don't you think, since, after myInt going out of scope, arr[] still has a reference to it till line 8?
arr[i] = myInt
creates a copy of the reference to new Integer(i)
, not a reference to myInt
; therefore, myInt isn't strictly required to exist after that assignment.