Reputation: 29
I have a question that in this statement in java
A z[]=new A[5];
how much the number of references that this statement will store in memory and does the z
reference points to z[0]
?
Upvotes: 0
Views: 635
Reputation: 103903
Given: A[] x = new A[5];
(Don't write A x[]
; it's legal java but not idiomatic at all. Consider it a style faux pas. Like misindenting your code). Let's assume this is inside a method (so, it is a local variable declaration, and not a field declaration).
This creates a new local variable of name 'x', restricted to point at objects, and can only point at instances of A[]
, or null
, and nothing else, verified by both the compiler and the runtime. It also instantiates a new array object on the heap, and will set the x
variable to point at this newly created object.
This pointer variable itself takes some space (4 or 8 bytes, depending on VM), but it'll be on the stack, just like in C.
So, what does new A[5]
take, memory-wise?
It creates a new object to represent the array itself. This object contains the following information: How many elements do I have, and what is my component type. This is again unlike C, where armed with solely a pointer to an array datastructure, you have no idea what data might be there and also no idea how much data is there. In java, neither is the case, but that info (length, and type) mean you need to store that in memory explicitly. You can observe this: x.length
would return 5, and x.getClass().getComponentType
would return A.class. On 64-bit VM, this object takes about 24 bytes total (4 for the size, 8 for the pointer to the component type, and a few extra bytes thrown in because the thing needs to identify that it is representing an array).
Following those 24 bytes there's 5 'slots', and each slot takes up as many bytes as the component type requires. How much is that? Depends on what A
is.
If A
is: byte
, short
, int
, long
, float
, double
, char
, boolean
, or anything else.
Then component size (in bytes) is, respectively: 1, 2, 4, 8, 8, 4, 8, 2, 1, and X, where X is 4 or 8 depending on the VM. These days, almost always 8 (64-bit VMs).
The VM may, during execution, inject some blank space in the memory tables because modern CPUs really really do not like dealing with things that aren't nicely placed on 64-bit borders. C compilers do the same thing.
Upvotes: 3