6

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?

user2249516
  • 281
  • 2
  • 5
  • 12
  • You actually build a pointer array, that's correct. So you need the sizeof(pointer) * array_size. Instancing a object you gonna link to an array index takes care about the actual memory allocation of the object. – schlingel Nov 20 '13 at 15:20
  • 2
    This question pretty much answers yours http://stackoverflow.com/questions/5564423/arrays-in-java-and-how-they-are-stored-in-memory – Ross Drew Nov 20 '13 at 15:24
  • Actually, in Java, there is only one type of object that has a variable size: array. Everything else has a predetermined size (String holds an array internally). – Durandal Nov 20 '13 at 16:41

3 Answers3

6

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.

Community
  • 1
  • 1
aga
  • 27,954
  • 13
  • 86
  • 121
4

int[] => array of ints

String [] => array of pointers to String instances

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

Bert F
  • 85,407
  • 12
  • 106
  • 123
0

Arrays are itself an object in Java so it will be always created in runtime. From Official tutorial:

One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.

// create an array of integers

anArray = new int[10];

If this statement is missing, then the compiler prints an error like the following, and compilation fails:

ArrayDemo.java:4: Variable anArray may not have been initialized.

Also another answer in StackOverflow.

Community
  • 1
  • 1
Anirban Nag 'tintinmj'
  • 5,572
  • 6
  • 39
  • 59