Search code examples
javaarraysinitializationinstance-variablesunexpected-token

1-initialaizing array and 2-initialaizing instance variables(java)


My question is that I can not quantify the elements of an array in the body of the class and I get an error:(Unexpected token) and I can only define it but not initialize it.

int[] a=new int[9];
a[7]=8;//error

Solution

  • For your first question: The array initializer (the statement with the curly brackets) will let you initialize the array on declaration.

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

    (see Array Initializers)

    Wrinting this is fine:

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

    because you are using the array initializer syntax on array declaration.

    But writing this is not ok, due to the specification defined above:

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

    Onto your second question:

    The snippet you provided is generally valid code, if it is provided inside a method. In a class body, the second line is not a variable declaration/initialization and therefore invalid code in a class body.

    What you can do however, is this:

    int[] array = new int[9]{ 0, 0, 0, 0, 0, 0, 0, 8, 0 }; 
    

    which is allowed and basically equal to what you asked. (Because by default, an int[] will initialize its values with 0)