1

I want to know if the datatype of an array is the datatype of each element or the whole array. For instance, will this code reserve 4 bytes or 16 bytes of RAM?

int[] collection = {30, 40, 50, 60};
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ahmed Maher
  • 25
  • 2
  • 7

2 Answers2

2

Each of the 4 int values use 4 bytes.

However the array uses a object header which is 8 - 12 bytes long in the OpenJDK (and like JVMS)

The object alignment is 8 bytes by default so the size of the object will be rounded up to a multiple of 8.

This means the object could be 24 to 32 bytes long.

The reference to this object will be 4 bytes unless you have a 64-bit JVM which has Compressed Oops disabled.

What is in java object header

Document -XX:ObjectAlignmentInBytes

Compressed OOPs

Community
  • 1
  • 1
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

This is an array of four elements, where each one is an int. Since a single int takes 4 bytes, the array will take a total of 4*4 = 16 bytes.

Mureinik
  • 297,002
  • 52
  • 306
  • 350