I know there are two ways to create an array with given initial value
int[] ary1 = new int[]{1,2,3,4};int[] ary1 = {1,2,3,4};
What exactly is the difference between those?
There is no difference in your example.
However, there is one extra feature that new type[] provides - array length:
Like so:
String[] names = new String[5];
Which makes a new String array with the capacity to hold 5 items. If one of the items is not populated, it will return null.
new String[5]; does not have 5 items in it. It has the capacity to hold 5 items but the way it is written each spot is actually null. #1 in how you would populate the array after you call new in a single command.Both of your statements will create and initialize an array. However, the following example illustrates a difference:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
print(new int[] { 1, 2, 3, 4 });
// print({ 1, 2, 3, 4 });// Won't be compiled
}
static void print(int[] arr) {
System.out.println(Arrays.toString(arr));
}
}
int[] ar1 = new int[] { 1, 2, 3, 4 }; int[] ar2 = { 1, 2, 3, 4 }; print(ar1); print(ar2);Both of the following are equivalent.
int[] ary1 = {1,2,3,4};
int[] ary1 = new int[] {1,2,3,4};
But the {} method can only be used when the array is declared. So
int[] ary1;
ary1 = {1,2,3,4}; // not permitted.
Nor is
for (int a : {1,2,3,4}) {
// do something
}
It has to be
for (int a : new int[] {1,2,3,4}) {
// do something
}