Arrays in Java and how they are stored in memory

arrays, java, memory

Solution

Arrays in Java store one of two things: either primitive values (`int`, `char`, ...) or references (a.k.a pointers).

So, `new Integer[10]` creates space for 10 `Integer` references only. It does not create 10 `Integer` objects (or even free space for 10 `Integer` objects).

Incidentally that's exactly the same way that fields, variables and method/constructor parameters work: they too only store primitive values or references.

Problem

I'm trying to understand the array setup in java. Why must you initialize space for each each object in the array, after you have created the array. How is it stored in memory like this: ``` [object][object] ``` or like this: ``` [*class]->[object] [*class]->[object] ``` In other words, what is actually being done in memory. Does `array[0] = new class()` just return a reference to a reserved location in memory, and the `class[] array = new class[10]` statement create something along the lines of 10 pointers, which are later assigned to by the new statements?

Original source

Related problems