1

I understand how to build arrays in Java, pretty easy. I'm just trying to wrap my head around what does it actually mean for Java arrays to be dynamically allocated. Thanks in advance for the help!

95C3ntS
  • 7
  • 5

2 Answers2

4

Since you understand how to build arrays in Java, you will have noticed that you can do

int[] x = new int[someVariable];

This creates an array of a size that is not known at compile-time, meaning that the array (or rather the space for it) cannot be allocated by the compiler, but has to be allocated at run-time, i.e. dynamically. So when this line of code executes, some object on the heap will be created, and the normal garbage collection mechanism will eventually clean it up when it is no longer used.

In Java, the same dynamic mechanism is also used for arrays where the size is known at compile-time, but in theory -- and in other languages -- there are statically allocated arrays.

Thilo
  • 241,635
  • 91
  • 474
  • 626
1

What does it mean for Java Arrays to be dynamically allocated?

This kind of purpose is not common.
I would say that it is rather right but a little bit misleading in the arrays context.
In Java all (objects, classes, primitives) is allocated at runtime : nothing is indeed allocated at compile.
So yes arrays are also dynamically allocated but dynamically allocated doesn't mean necessarily resizable : as evidence ArrayLists and arrays are allocated at runtime but only the former is resizable.

davidxxx
  • 104,693
  • 13
  • 159
  • 179