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?
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.
int[]
=> array of ints
String []
=> array of pointers to String instances
int[][]
=> array of pointers to (separate, disparate) int[] arrays
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