0

In Java, how the check number of bytes allocated to an array after it's declaration? For example:

int[] a = new int[10]; 

Array 'a' is allocated 4*10 bytes since the size of int is 4 bytes and there are 10 integer elements. Is there a non-manual way of doing this?

wpercy
  • 9,636
  • 4
  • 33
  • 45
java_user
  • 75
  • 11
  • Check this [thread](http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object). – Ralf Feb 18 '16 at 21:01

2 Answers2

1

In Java there is no operator like sizeof in C to get the size of the array element. So there is at least no straightforward way.

By the way, no memory is allocated during declaration, only during initialization.

Declaration:

int[] a;

Initialization:

a = new int[10]; 
Frank Puffer
  • 8,135
  • 2
  • 20
  • 45
1

Actually the size of int[10] is 56 bytes or more (depending on your JVM).

  • 10 * 4 = 40 bytes for the ten ints
  • 4 bytes to store the array length
  • 8 bytes for the Java object
  • 4 bytes to make the size of the object a multiple of 8 (alignment).

But this all depends on the JVM and memory architecture of your operating system. java.lang.instrumentation.Instrumentation provides a way to calculate sizes of an object, as explained in this answer.

Community
  • 1
  • 1
wero
  • 32,544
  • 3
  • 59
  • 84