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:27

I assume when you're referring to "static memory" you're referring to the heap. In Java, the heap serves a similar purpose to the "static data segment" you mentioned. The heap is where most objects are allocated, including arrays. The stack, on the other hand, is where objects that are used only during the life of a single method are placed.

查看更多
贪生不怕死
3楼-- · 2019-04-03 09:29

In Java you've merely asked that a strongly typed reference to an array be stored statically for the class Test. You can change what a refers to at runtime, which includes changing the size. This would be the C equivalent of a static storage of an int*.

查看更多
贼婆χ
4楼-- · 2019-04-03 09:41

Static has a different meaning in Java. In Java when you declare a variable as static it is a class variable and not an instance variable.

查看更多
太酷不给撩
5楼-- · 2019-04-03 09:44

You are creating a new array, not modifying the old one. The new array will get its own space and the old one will be garbage-collected (so long as nobody else holds a reference to it).

查看更多
The star\"
6楼-- · 2019-04-03 09:47

The value of a is just a reference to an object. The array creation expression (new int[2]) creates a new object of the right size, and assigns a reference to a.

Note that static in Java is fairly separate to static in C. In Java it just means "related to the type rather than to any particular instance of the type".

查看更多
beautiful°
7楼-- · 2019-04-03 09:51

In Java, a static variable exists as part of the class object. Think of it as an instance variable for the class itself. In your example, a is a reference variable, which refers to some array (or no array at all, if it is null), but the array itself is allocated as all arrays are in Java: off the heap.

查看更多
登录 后发表回答