When you declare an array you can use the syntax public int[] arr = {1,2};
, but after declaration when you try to initialize it elsewhere (say in a method) you cannot use the shorthand you need to do it like arr = new int[]{1,2};
.
This is because when you are declaring an array and you initialize it with some values public int[] arr = {1,2};
the space for the array members (two in this case) is allocated and cannot be modified later unless you create a new array object and assign it to that field again. The final length
property of the array object is set when you declare it using an array initializer.
But later on when you do arr = new int[]{1,2};
you are actually creating a new array object and assigning to the already declared field.
TL;DR:
The array initializer syntax {}
is only allowed during array declaration where the array constructor syntax new type[]{}
is allowed after declaration in an assignment statement.