1
public class Test1 {
    public static void main () {
        int N = 10;
        int M = 100000;
        for(int i =0; i< N; i++) {
             int[] box = new int[M];
        }
    }
}

Will this code cause cause the memory to be allocated for the array with size equal to M elements for each iteration of the for loop?

  • 4
    Yes. But since after each iteration, no reference on the new array exists, it will be garbage-collected with the next gc-run. – Turing85 Sep 02 '20 at 15:40
  • [A similar, but not the same](https://stackoverflow.com/questions/7277507/how-bad-is-declaring-arrays-inside-a-for-loop-in-java) – dbl Sep 02 '20 at 15:45
  • The compiler will probably only allocate the array once, if that. – NomadMaker Sep 02 '20 at 15:46
  • @NomadMaker the JIT-compiler maybe. But the JIT-compiler may even omit the whole loop. – Turing85 Sep 02 '20 at 15:56
  • 1
    Even javac should be able to optimize out the array, and maybe the loop. There are no side effects, because no box is actually instanciated. BTW, java code standards have classes beginning with an upper case letter (Box). – NomadMaker Sep 02 '20 at 15:59
  • @NomadMaker where did you see a class that starts with small leter? Do you point at the local variable named `box`? This one in particular is fine, while variables `N` and `M` should infact start with a small letter, respectivly be renamed to `n` and `m`. – dbl Sep 02 '20 at 16:05
  • 1
    Sorry, my bad. I misread the array as a type name. As for N and M, I assumed they were constants (even without the final). – NomadMaker Sep 02 '20 at 16:07

1 Answers1

2

Yes. But since no reference on the new array exists outside the loop, each instance is eligible for garbage-collection and will most probably be collected with the next gc-run.

Turing85
  • 18,217
  • 7
  • 33
  • 58