Arrays in Java and how they are stored in memory

If you are familiar with C/C++ you can think of Java object references as pointers to objects (or pointers to structs). So:

Person p = new Person();
p.setName("Helios");

is:

  • declare a p pointer to a Person struct (in the stack)
  • reserve memory for and initialize Person struct
  • assign its address to p
  • execute method setName on object referenced by p

So when you are doing:

Person[] ps = new Person[5];

you are reserving an array of 5 references to Person. Next you will have to create each real person and assign each reference to a place in the array.

Edit: the (almost) C/C++ version of the previous code

class Person { ... };
typedef PersonStruct* Person; // I don't remember if this declaration is ok
Person p = new PersonStruct();
p -> setName(...);

Person[] ps = new Person[5]; 
// ps is a variable in the stack pointing to the array in the heap
// (being the array five references to the PersoStruct)

and you could do

ps[3] = p;

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.