-2

As I understand it, if I want to create an empty array (to fill later during my program's runtime) I have to set its size, so that Java knows how much memory to allocate. So, if I create the following int array:

int[][] board = new int[3][3];

Java will allocate 3x3x4 bytes of RAM.

But if a String is an array of characters, how can Java predict how much RAM is needed without knowing how long my String will be? For example:

String[] nameList = new String[5]

The names I put in this array could be any amount of characters long. How is memory allocated in that case?

YepNope
  • 29
  • 3
  • 2
    Variables to objects use objects *reference* (some number which is unique identifier of object) and those references will be stored in array (and they have fixed size). – Pshemo Jun 02 '22 at 13:48
  • 3
    The title of your question doesn't really reflect the body – Ivo Beckers Jun 02 '22 at 13:49
  • 2
    `Java will allocate 3x3x4 bytes of RAM.` Your assomption is wrong – Maurice Perry Jun 02 '22 at 13:49
  • 2
    BTW while `int[4]` will hold 4 ints, `int[2][4]` will hold 2 *references* to 1D arrays where each have `4` ints. – Pshemo Jun 02 '22 at 13:50
  • 1
    Possibly related: [What is the difference between a variable, object, and reference?](https://stackoverflow.com/q/32010172), [How big is an object reference in Java and precisely what information does it contain?](https://stackoverflow.com/q/981073) – Pshemo Jun 02 '22 at 13:58

2 Answers2

6

The array doesn't hold any Strings; it holds references to Strings, which are initially null.

Creating Strings and assigning them to array elements

nameList[0] = "foo";

Has no effect whatsoever on the amount of memory allocated to the array.

The exact number of bytes of memory allocated to the array to hold each reference is system dependant.

Primitive arrays hold the actual value (not a reference to the value), and use a known amount of memory per element.

Bohemian
  • 389,931
  • 88
  • 552
  • 692
  • Agreed. Maybe you can expand on why `int[]` is different than `Object[]` ? I *think* the OP has not this cristal clear, given how the question is phrased... – GPI Jun 02 '22 at 13:50
2

An array of objects is actually an array of references to objects. By default all such references are null. When you change some item of the array you actually change the reference.

Rostislav Krasny
  • 565
  • 3
  • 12