I know that Arrays of primitive type are implicitly initialized to 0 in java. So if I have a code :
public class Foo{
public static void main(String args[]){
int[] arr = new int[50];
for(int i = 0; i < 30; i++){
arr[i] = i;
}
for(int i = 0; i < 30; i++){ // This Line
System.out.println(arr[i]);
}
}
}
I want to know if memory from arr[30] to arr[49] would already have been reclaimed by garbage collector at the line which has the comment?
I want to know if memory from arr[30] to arr[49] would already have been reclaimed by garbage collector at the line which has the comment?
No, absolutely not. The array is a single object. It's either reachable, or it's not reachable... and in this case, it's still reachable.
In a more complex example, if this were a String[]
, I wouldn't expect the strings referenced by elements arr[30]
to arr[49]
to be eligible for garbage collection, either. A very smart GC might be able to tell which parts of an array are unused and not include those in GC roots, but I don't think I've ever seen that. (It would have to know that no other code ever had a reference to the array, for one thing. It seems an unusual situation, and therefore one probably not worth optimizing.)
See more on this question at Stackoverflow