Is there any difference between
int[] numbers = new int [] {1,2,3,4,5};
and
int[] numbers = {1,2,3,4,5};
or do they express the same?
Which one shall be used?
You can have a look at the below method to understand the difference:
public int[] getFewInts() {
// You can't directly return {1,2,3,4,5};
return new int [] {1,2,3,4,5};
}
If you wanted to return an int[] array from a method in a single line, you can do that by simply new int [] {1,2,3,4,5}; where as you can't do that with the other one i.e., {1,2,3,4,5}.
The same concept applies when you want to pass the int[] type as a parameter to a method.
int[] array; array = {1,2,3}; The notation can only be used during the declaration.
new int[] {...}must be used when the assignment is separated from the variable declaration (which is not the case in the OP's question). Doesn't matter if it is a field or a local variable.