How are static arrays stored in Java memory?

2019-04-03 09:25发布

So in a language like C, memory is separated into 5 different parts: OS Kernel, text segment, static memory, dynamic memory, and the stack. Something like this:

Memory Layout

If we declared a static array in C, you had to specify it's size beforehand after that would be fixed forevermore. The program would allocate enough memory for the array and stick it in the static data segment as expected.

However I noticed that in Java, you could do something like this:

public class Test {
        static int[] a = new int[1];

        public static void main( String[] args ) {
                a = new int[2];
        }
} 

and everything would work as you'd expect. My question is, why does this work in Java?

EDIT: So the consensus is that an int[] in Java is acts more similarly to an int* in C. So as a follow up question, is there any way to allocate arrays in static memory in Java (if no, why not)? Wouldn't this provide quicker access to such arrays? EDIT2: ^ this is in a new question now: Where are static class variables stored in memory?

7条回答
虎瘦雄心在
2楼-- · 2019-04-03 09:53

In java any time you use the word new, memory for that object is allocated on the heap and a reference is returned. This is also true for arrays. The int[] a is just the reference to new int[1]. When you do new int[2], a new array is allocated and pointed to a. The old array will be garbage collected when needed.

查看更多
登录 后发表回答