Why doesn't the following work to initialize an array?
public class TestArrays {
private static int[] numbers;
public static void main(String[] args) {
numbers = {1,2,3}; //error
}
} //class
but yes in this way?
public class TestArrays {
private static int[] numbers;
public static void main(String[] args) {
int[] arr = {1,2,3};
numbers = arr;
}
} //class
Java allows you to initialize an array using curly braces as follows:
Said format, only in the case that we are declaring the variable , can be simplified to
Instead, the first way does work without a declaration:
Why? Well, aside from why it's defined that way in the language specs, we'd have to ask its creator to find out why he restricted the short form to variable declarations. My opinion is that, if we admit the following:
It would not be totally clear if in the second assignment we are creating a new array of the same size or if we are replacing the values in the object (array) that already existed. By forcing ourselves to put
new int[]
, the doubt is clarified.To complement @Pablo Lozano's answer. The java specification states the correct syntax and where it is used, in the following paragraphs:
JLS 10.6 :
Which in Spanish would be:
Where they define the initializer array as:
Where an array creation expression is defined as: