I am initializing an array data like this :
public class Array {
int data[] = new int[10];
/** Creates a new instance of Array */
public Array() {
data[10] = {10,20,30,40,50,60,71,80,90,91};
}
}
NetBeans points an error at the line
data[10] = {10,20,30,40,50,60,71,80,90,91};
How can I solve the problem?
Syntax
Example :
Maybe this will work:
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:
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 accessdata[0]
todata[9]
because index of arrays in Java is 0-based). Accessingdata[10]
will throw an ArrayIndexOutOfBoundsException.When you create an array of size 10 it allocated 10 slots but from 0 to 9. This for loop might help you see that a little better.