There are a couple of errors in your code:
Declaration: The assignment operator =
has two operands: right-side, which is the variable receiving the value, and left-side, which is the value being assigned. The left-side expression must construct an array. You will probably note that new a[4]
isn't a valid construction for an array. It should be new int[4]
instead.
Initialization: The {x,y,...}
syntax can only be used when initializing an array. new int[x];
will allocate a new array with capacity/length x
, and initialize every element in the array with a default value (0
in the case of int
s). Once there, you can not initialize the array again with constant values with the {x,y,z}
construct.
Also, the way you've declared the array (int a[]
) is discouraged, use int[] a
instead. It's a clearer syntax.
Try this:
int[] a = new int[]{ 12,14,15,17,21};
Note you could also have done:
// Declaring a is an array of ints
int[] a;
// Initialization and assignment to a.
// Notice the array length isn't explicitly given.
a = new int[]{ 12,14,15,17,21 };
Or else:
// Declaring a is an array of ints
int[] a;
// Initializing a as an empty array with 5 elements (all of them will be 0)
a = new int[5];
a[0] = 12;
a[1] = 14;
a[2] = 15;
a[3] = 17;
a[4] = 21;
You might find the Arrays page of the Java Tutorials useful.
EDIT As a side note, as rgettman pointed out in his comment, there shouldn't be a semicolon at the end of the void
method signature. And take into account that if you allocate a new int[4]
, the last valid index to access it will be 3 (a[3]
). a[4]
will throw an ArrayIndexOutOfBoundsException
.