When I create a new array, I do something like this.
int[] anArray = {1, 2, 3};
But I’ve seen some people do something like.
int[] anArray = new int[] {1, 2, 3};
I understand what it does, but I don’t understand the purpose of it. Is there a benefit of doing it one way over another?
Thanks
There’s no difference in behaviour where both are valid. They are covered in section 10.6 and 15.10 of the Java language specification.
However the first syntax is only valid when declaring a variable. So for example:
As for the purpose – the purpose of the first syntax is to allow variable declarations to be more concise… and the purpose of the second syntax is for general-purpose use as an expression. It would be odd to disallow the second syntax for variable declarations, just because the more concise syntax is available.