Initialize Java arrays

8

Why does not 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
    
asked by Orici 07.03.2018 в 13:08
source

2 answers

13

Java allows you to initialize an array using keys in the following way:

int [] array = new int[] {1,2,3};

Said format, only in case we are declaring the variable , it can be simplified to

int [] array = {1,2,3};

On the other hand, the first form does work without a declaration:

int array[];
array= new int[] {1,2,3};

Why? Well, apart from because it is defined like this in the language specifications, we would have to ask its creator to find the reason that led him to restrict the short form to the declaration of variables. My opinion is that, if we admit the following:

int [] array = {1,2,3};
array = {2,3,43};

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 us to put new int[] clarifies the doubt.

    
answered by 07.03.2018 / 13:21
source
3

To complement the response of @Pablo Lozano. The java specification establishes the correct syntax and where it is occupied, in the following paragraphs:

JLS 10.6 :

  

An array initializer may be specified in a declaration (§8.3, §9.3,   §14.4), or as part of an array creation expression (§15.10), to create   an array and provide some initial values.

That in Spanish would be:

  

An array initializer can be specified in a declaration   (§8.3, §9.3, §14.4), or as part of an expression of creation of   arrangement (§15.10), to create an arrangement and provide some values   initials.

Where they define the array initializer as:

ArrayInitializer:
    { VariableInitializersopt ,opt }

VariableInitializers:
    VariableInitializer
    VariableInitializers , VariableInitializer

Where an array creation expression is defined as:

ArrayCreationExpression:
    new PrimitiveType DimExprs Dimsopt
    new ClassOrInterfaceType DimExprs Dimsopt
    new PrimitiveType Dims ArrayInitializer 
    new ClassOrInterfaceType Dims ArrayInitializer

DimExprs:
    DimExpr
    DimExprs DimExpr

DimExpr:
    [ Expression ]

Dims:
    [ ]
    Dims [ ]
    
answered by 07.03.2018 в 13:57