What does a Java array look like in memory?

In Java, an array stores either primitive values (int, char, …) or references (a.k.a pointers) to objects.

When an object is created by using “new”, a memory space is allocated in the heap and a reference is returned. This is also true for arrays, since arrays are objects in Java.

1. Single-dimension Array

int arr[] = new int[3];

The int[] arr is just the reference to the array of 3 integer. If you create an array with 10 integer, it is the same – an array is allocated and a reference is returned.


2. Two-dimensional Array

How about 2-dimensional array? Actually, we can only have one dimensional arrays in Java. A 2-dimension array is just an array of 1-dimension arrays.

int[ ][ ] arr = new int[3][ ];
arr[0] = new int[3];
arr[1] = new int[5];
arr[2] = new int[4];


Multi-dimension arrays are similar as you can image.

3. Where are they located in memory?

Arrays are also objects in Java, so how an object looks like in memory applies to an array.

As we know that JVM runtime data areas include heap, JVM stack, and others. For a simple example as follows, let’s see where the array and its reference are stored.

class A {
	int x;
	int y;
public void m1() {
	int i = 0;
public void m2() {
	A a = new A();

With the above declaration, let’s invoke m1() and see what happens:

  1. When m1 is invoked, a new frame (Frame-1) is pushed into the stack, and local variable i is also created in Frame-1.
  2. Then m2 is invoked inside of m1, another new frame (Frame-2) is pushed into the stack. In m2, an object of class A is created in the heap and reference variable is put in Frame-2. Now, at this point, the stack and heap looks like the following:


Arrays are treated the same way as objects, so where array are located in memory is straight-forward.

6 thoughts on “What does a Java array look like in memory?”

  1. Array is also class and extends Object. If an array contains primitives, e.g. int, it is still stored in the heap as an array of primitives. An array is a single & contiguous object. When/how it is garbage collected conforms to rules for regular objects – its not reachable from any live threads or any static references.

  2. But what do they look like in memory? e.g., for a multidimensional array of primitives, how are contiguity and alignment realized? What about before/after gc?

  3. A slight mistake in the figure: Frame-1 should have a rectangle with i, not a. And in Frame-2, the rectangle should contain a, not i.

Leave a Comment