So in a language like C, memory is separated into 5 different parts: OS Kernel, text segment, static memory, dynamic memory, and the stack. Something like this:
If we declared a static array in C, you had to specify it's size beforehand after that would be fixed forevermore. The program would allocate enough memory for the array and stick it in the static data segment as expected.
However I noticed that in Java, you could do something like this:
public class Test {
static int[] a = new int[1];
public static void main( String[] args ) {
a = new int[2];
}
}
and everything would work as you'd expect. My question is, why does this work in Java?
EDIT: So the consensus is that an int[]
in Java is acts more similarly to an int*
in C. So as a follow up question, is there any way to allocate arrays in static memory in Java (if no, why not)? Wouldn't this provide quicker access to such arrays?
EDIT2: ^ this is in a new question now: Where are static class variables stored in memory?
Normally, arrays are stored in the same area of memory as any other variable type defined at the same point in the program source. If it is a global or static array, it will be stored in the data segment; if it is local to a function (and not static) it will be stored on the stack.
Where is the memory allocated for an array in Java? Memory is allocated in Heap are for the Array in Java. In Java reference types are stored in the Heap area. As arrays are also reference types, (they can be created using the “new” keyword) they are also stored in the Heap area.
Storage Area of Static Variable in Java Method area section was used to store static variables of the class, metadata of the class, etc. Whereas, non-static methods and variables were stored in the heap memory. After the java 8 version, static variables are stored in the heap memory.
Storage of Arrays As discussed, the reference types in Java are stored in heap area. Since arrays are reference types (we can create them using the new keyword) these are also stored in heap area.
The value of a
is just a reference to an object. The array creation expression (new int[2]
) creates a new object of the right size, and assigns a reference to a
.
Note that static
in Java is fairly separate to static
in C. In Java it just means "related to the type rather than to any particular instance of the type".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With