I am wondering,
What's exactly the difference between these two ways of initializing an array of primitives:
int[] arr1 = new int[]{3,2,5,4,1};
int[] arr2 = {3,2,5,4,1};
and which one is preferred ?
I am wondering,
What's exactly the difference between these two ways of initializing an array of primitives:
int[] arr1 = new int[]{3,2,5,4,1};
int[] arr2 = {3,2,5,4,1};
and which one is preferred ?
There is none, they produce exactly the same bytecode. I think it may be that the second form wasn't supported in older versions of Java, but that would have been a while back.
That being the case, it becomes a matter of style, which is a matter of personal preference. Since you specifically asked, I prefer the second, but again, it's a matter of personal taste.
As others have mentioned, they are equivalent and the second option is less verbose. Unfortunately the compiler isn't always able to understand the second option:
public int[] getNumbers() {
return {1, 2, 3}; //illegal start of expression
}
In this case you have to use the full syntax:
public int[] getNumbers() {
return new int[]{1, 2, 3};
}
There is no difference between the two statements. Personally speaking, the second one is preferred. Because you have all the elements specified in the braces. The compiler will help you to compute the size of the array.
So no need to add int[]
after the assignment operator.
In your case, these two styles end up same effect, both correct, with the second one more concise. But actually these two styles are different.
Remember arrays in java are fixed length data structures. Once you create an array, you have to specify the length.
Without initialization, the first case is
int[] arr1 = new int[5];
The second case it would be
int[] arr2 = {0,0,0,0,0};
You see the difference? In this situation, the first style is preferred as you don't have to type all those default initial values manually.
To me, the only big difference between the two styles is when creating an array without explicit initialization.
In this case, the second one because it's prettier and less verbose :)
useful in this situation
void foo(int[] array) {
}
calling with a literal
// works
foo(new int[]{5, 7})
//illegal
foo({5, 7})
Adding to @Paul Bellora's answer, only the second option will work if you're trying to initialize a primitive array using ternary operator
int[] arr1 = false ? {} : {1,2}; // doesn't work
int[] arr2 = false ? new int[]{} : new int[]{1,2}; // works
© 2022 - 2024 — McMap. All rights reserved.