JVM memory is divided into: 1. Method Area 2. Heap Area 3. Stack 4. PC Register 5. Native Stack
Now suppose I have a class having property of say "int[] dealCodes"(array of int primitive). As per memory management once deal code is initialized, there would be contiguous memory allocation of (total_elements * 4 bytes) in memory. So if array size is 10 then there will be 40 bytes allocation in JVM memory.
My question is in which area this 40 bytes will be allocated (heap or stack)?
My understanding about array is: it's just like any other object and resides under heap area but don't know about primitives to which array points to.
Also want to know about similar scenario when array holds references (e.g. array of type Employees). I think in this case, everything will be in heap area. As these are references then array will hold 4 bytes for each reference (32 bit system) and these references will point to objects of varying size. Array memory allocation will be calculated on basis of reference size not object size.
Please help me to get clarity on above 2 points.
Objects are always Heap allocated so your dealCodes
will be
allocated there only but the total memory allocated is more than 40 bytes.
12 bytes (Header) + 4 bytes (Length of Array) + 40 bytes (4 bytes * 10 ints) = 56 bytes
Same thing applies to an array of Employee
objects as well except that each array element is now a reference to Employee object, so the Shallow Heap
occupied by employees array is still 56 bytes while the Retained Heap
depends on the size of each Employee object.
You can use VisualVM
in JDK_HOME/bin directory to take a snapshot of your program/application, see the memory occupied by each object, both shallow and retained heap sizes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With