data[10] = {10,20,30,40,50,60,71,80,90,91};
The above is not correct (syntax error). It means you are assigning an array to data[10]
which can hold just an element.
If you want to initialize an array, try using Array Initializer:
int[] data = {10,20,30,40,50,60,71,80,90,91};
// or
int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};
Notice the difference between the two declarations. When assigning a new array to a declared variable, new
must be used.
Even if you correct the syntax, accessing data[10]
is still incorrect (You can only access data[0]
to data[9]
because index of arrays in Java is 0-based). Accessing data[10]
will throw an ArrayIndexOutOfBoundsException.
Best Answer
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).
For primitive types:
For classes, for example
String
, it's the same:The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required.