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?

7
  • 4
    Yes. But since after each iteration, no reference on the new array exists, it will be garbage-collected with the next gc-run. Commented Sep 2, 2020 at 15:40
  • A similar, but not the same Commented Sep 2, 2020 at 15:45
  • The compiler will probably only allocate the array once, if that. Commented Sep 2, 2020 at 15:46
  • 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). Commented Sep 2, 2020 at 15:59
  • 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). Commented Sep 2, 2020 at 16:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.