-1

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
amz
  • 32
  • 6

1 Answers1

0

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)

maloomeister
  • 2,461
  • 1
  • 12
  • 21
  • Thanks you for answering my first question. – amz Feb 04 '21 at 08:32
  • Thanks you for answering my first question but for the second one I can not understand what the problem is. you define an instance variable called array for your class then you initialize its 8th element with 8.then each object that is made of class the 8th element has 8 value by default. Why is this illegal in Java?Why can't we quantify it in the body of the class? – amz Feb 04 '21 at 08:48
  • I edited my answer and added a bit more detail. "_Why is this illegal in Java?_" This is simply how it is specified. If your questions are answered, please make sure to [accept the answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235). – maloomeister Feb 04 '21 at 08:56