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:
public void foo(String[] args) {}
...
// Valid
foo(new String[] { "a", "b", "c" };
// Invalid
foo({"a", "b", "c"});
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.
One would use the second way, if the declaration should be done before the initialization.
int[] arr;
arr = { 2, 5, 6, 12, 13 };
Would not work, so you use:
int[] arr;
arr = new int[]{ 2, 5, 6, 12, 13 };
instead. Another way is to declare another variable:
int[] arr;
int[] tmparr = { 2, 5, 6, 12, 13 };
arr = tmparr;
So if you don't need to seperate the declaration from the initialization, it's only a matter of clean code (use either one consistently).
They are almost the same thing, but the first is applicable for object assignment like:
int[] anArray = {1, 2, 3};
The other one is more globaly like
callingMyMethod(new Object[]{object1,object2});
The wrong syntax would be
callingMyMethod({object1,object2});
Let's take it further
These initialization are right:
Object[] objeto={new Object(), new Object()};
Object[] objeto=new Object[]{new Object(), new Object()};
Also right:
Object[] objeto;
objeto=new Object[]{new Object(), new Object()}
But as Jon suggested this is wrong:
Object[] objeto;
objeto={new Object(), new Object()};
Why? Array Initializer And Array Creation Expression
Anyway both of your syntax are correct. There is no benefit on one against the other.
Interesting reading on this subject:
Arrays on Oracle Official documentation
This have also been covered on this thread
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With