打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
What does a Java array look like in memory?

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.

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];

Multi-dimensional arrays use the name rules.

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;	m2();} 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 like objects, so how array locates in memory is straight-forward.

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Gallery of Processor Cache Effects
java out of memory的代码
Debugging Software Crashes in C and C - II
array_chunk() 分隔数组
JDK5的新特性:增强for
Java排序算法(四)希尔排序2
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服