Array declaration and initialization in Java [duplicate]
Asked Answered
A

2

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

Can someone explain why the last one is wrong and the reason we can do #2?

Altair answered 1/6, 2021 at 3:35 Comment(0)
F
2

As a direct answer to your question, this is the case because the Java language was defined in this way. When we declare a new field or local variable, we may initialize it by either an expression (new int[] { 1, 2, 3 }) or an array initializer ({1, 2, 3}). When assigning to a previously declared field or local variable, we may only use an expression.

I can only speculate why this difference exists, but I assume it has something to do with the fact that arrays are reified, that is, at run-time, an array knows the type of its elements. This means that you need to specify the element type when you want to create a new array. When initializing an array, the element type is readily available because the type of the array is explicitly specified, but in an expression, it isn't, at least not in general. One could of course try to infer the type of the elements, but the language designers chose not to do that.

Folkway answered 1/6, 2021 at 5:43 Comment(0)
A
1

You can check for yourself how the compiler works. It implicitly adds this construct:

new int[]

to the array initializer, and this code:

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

becomes this after compilation:

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

See documentation:
Java Language and Virtual Machine Specifications
10.6. Array Initializers
15.10. Array Creation and Access Expressions

Alvinia answered 1/6, 2021 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.