In java, I can initialize an array with predefined content either by :
int[] myArr = new int[]{1,2,3};
Or by :
int[] myArr = {1,2,3};
Essentially, is there any difference between these two ways ? Are they completely identical in Java ? Which way is better and why?
In your case there is no difference.
There will be a difference when you are not assigning your array
to variable and doing inline creation.
for example, conside there is method, which takes an array as argument.
private void someX(int[] param){
// do something
}
Your case:
someX(myArr); // using some declared array .I.e your case
Now see the difference while calling it in other cases.
someX(new int[] {1,2,3}); // yes, compiler satisfied.
someX({1,2,3}); //Error. Sorry boss, I don't know the type of array
is there any difference between these two ways ? Are they completely identical in Java ?
No there is no difference. Both of them will create an array of length 3
with the given values.
The 2nd one is just a shorthand of creating an array where you declare it. However, you can't use the 2nd way of creating an array, at any other place than the declaration, where the type of array is inferred from the declared type of array reference.
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