Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation for Object Arrays [duplicate]

In my computer science course, we were taught that when you create an array, the JVM will allocate the memory automatically depending on the size of the array. For example if you create an integer array with a size of 10, the JVM would allocate 10 * 32 Bits of data to that array.

My question is, how exactly does this process work when you create arrays of object that have varying sizes? For example a String object. When you create an array of 10 Strings, is any memory actually reserved on the system for these strings, or since they are just pointers, memory allocation isn't necessary?

like image 768
user2249516 Avatar asked Nov 20 '13 15:11

user2249516


2 Answers

Since the String is a class which extends the Object class, and objects in Java are passed (and stored in variables) by reference, the array of strings is an array of references to String objects. So, when you do

String[] a = new String[10];

you're creating an array of references, where the size of every reference (not the object it's pointing to) is already known (32 bits for 32-bit machines, and 64 bits for 64 bits machines).

Upd: as Jon Skeet said in one of his answers the size of an actual reference may be the same as a native pointer size, but it's not guaranteed.

like image 174
aga Avatar answered Sep 20 '22 23:09

aga


int[] => array of ints

String [] => array of pointers to String instances

int[][] => array of pointers to (separate, disparate) int[] arrays

like image 44
Bert F Avatar answered Sep 17 '22 23:09

Bert F