9

for example: why this statement long[] n= new long[]; is wrong but this statement long[][] n= new long[1][]; is right? How does the memory know how much memory needs to be assigned to the object in the second statement?

1
  • Simple but excellent question! Commented Mar 28, 2014 at 15:48

2 Answers 2

9

How does the memory know how much memory needs to be assigned to the object in the second statement?

Two things to remember here to figure out what's going on:

  • 2D Java arrays aren't square, they're arrays of arrays.
  • You specify the size of an array when it's created.

So in this example, you're creating an array of longs (of size 1) to hold another array of longs - but you're not yet creating the second array (so you don't need to specify how large it will be.) In effect, the first array provides an empty "slot" (or slots if the outer array is longer than 1) for the inner array(s) to sit in - but the inner array(s) haven't yet been created, so their size doesn't need to be specified.

It doesn't just create an array of arbitrary length at all, it simply doesn't create any inner arrays.

You can perhaps see this more clearly if you try to access or store a long in the 2D array:

long[][] x = new long[2][];
x[0][0] = 7;

...will produce a NullPointerException (on the second line), because there is no inner array there to access.

In the first example that doesn't compile, you're trying to actually create an array of longs, but not giving it a dimension, hence the error.

2

when you write this - long[][] n= new long[1][];

you are creating array of arrays of long but you are not actually initializing those arrays right now

So if you do n[0] == null it will return true

that way you are free to initialize new array in any point of time later-

n[0] = new long[10];

So the point is - you need to provide size while initializing your array , that is why long[] n= new long[]; is wrong

Not the answer you're looking for? Browse other questions tagged or ask your own question.