After reading, I came to know that, arrays in Java are objects. The name of the array is not the actual array, but just a reference. The new operator creates th
This generates an array of size 5, with 5 null elements:
int[] myArray = new int[5];
If the values aren't something you know at compile time, this is probably more useful. E.g.
int[] myArray = new int[blah.size()];
for (int i = 0; i < blah.size() ; i++) {
myArray[i] = getFoo(blah.get(i));
}
If you knew the size ahead of time, you could use the other form.
int[] myArray = {blah.get(0), blah.get(1), blah.get(2)};
The following are equivalent (compile to the same bytecode), and generate an array with inferred size 3, with three elements, 5, 7, and 3. This form is useful if there are fixed set of values, or at least a fixed size set of values.
int[] myArray = new int[]{5,7,3};
int[] myArray = {5,7,3};
Otherwise you could accomplish the same thing with the longer form:
int[] myArray = new int[5];
myArray[0] = 5;
myArray[1] = 7;
myArray[2] = 3;
But this is unnecessarily verbose. But if you don't know how many things there are, you have to use the first form.