Why when I try to initialize the array like that it gives me an error
package practicejava;
class Test {
public static void main(String[] args) {
int[] array;
array ={};
}
}
Why the following code shows me an error?
Why when I try to initialize the array like that it gives me an error
package practicejava;
class Test {
public static void main(String[] args) {
int[] array;
array ={};
}
}
Why the following code shows me an error?
Change as follow:
int[] array;
array = new int[]{};
Your current way of assigning the array is invalid.
you have to declare array size in array like as below
array = new int[5];
The array needs to be declared on the same line of code as:-
int[] array = new int[]{...};
The first line of your code that is:-
int [] array = {...}
This line is allowed by Java and is just a shorthand notation for the above declaration. Note that, this is only allowed if the declaration and initialization of the array is done simultaneously (the allocation of array is handled internally and is done accordingly to the number of elements).
The line
int [] array;
just creates a reference in the stack which is null that is it doesn't point to anything.
But, when you do array = {...}
, it is no longer valid as the memory needs to be allocated prior to initialization. Java does not handle such initialization internally.
So, it is recommended to initialize
array = new int[]{...}
instead.