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?
array. length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array.
We need to give the size of the array because the complier needs to allocate space in the memory which is not possible without knowing the size. Compiler determines the size required for an array with the help of the number of elements of an array and the size of the data type present in the array.
The length of an array equals the number of elements it can hold. The last index of an array is array. length-1 .
Note that as the arrays in Java are dynamically allocated, we do not specify any dimension or size of the array with the declaration. The above declaration tells the compiler that there is an array variable 'myarray' of type int which will be storing the integer type values in it.
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:
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.
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
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