- ✅
int[] array = new int[]{1,2,3};
- ✅
int[] array = {1,2,3};
- ✅
int[] array; array = new int[]{1,2,3};
- ❌
int[] array; array = {1,2,3};
Can someone explain why the last one is wrong and the reason we can do #2?
int[] array = new int[]{1,2,3};
int[] array = {1,2,3};
int[] array;
array = new int[]{1,2,3};
int[] array;
array = {1,2,3};
Can someone explain why the last one is wrong and the reason we can do #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.
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
© 2022 - 2024 — McMap. All rights reserved.