Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What Does a Java Array Look Like in Memory?

DZone's Guide to

What Does a Java Array Look Like in Memory?

· Java Zone
Free Resource

Never build auth again! The Okta Developer Platform makes it simple to implement authentication, authorization, MFA and more in Java applications. Get started with the free API.

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

When an object is creating by using “new”, memory is allocated on the heap and a reference is returned. This is also true for arrays.

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.

one-dimension-array-in-java





2. Two-dimensional Array

How about 2-dimensional array? Actually, we can only have one dimensional arrays in Java. 2D arrays are basically just one dimensional arrays of one dimensional arrays.

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

Array-in-Memory-Java












Multi-dimensional arrays use the name rules.

3. Where are they located in memory?

From the above, there are arrays and reference variables in memory. 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;
	m2();
}
 
public void m2() {
	A a = new A();
}
 
...
  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. When 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:

Java-array-in-memory

Arrays are treated the same way like objects, so how array locates in memory is straight-forward.

 

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Published at DZone with permission of Ryan Wang. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}