One can allocate arrays by providing the list of their elements in square brackets: e.g., new int[0] creates an array of ints with one element: the value 0; new int[2, 3] creates an array of ints with two elements: the values 2 and 3.


Array initializers list the elements in square brackets


Array initializers list the elements in curly braces

Here is what's right.

In Java, arrays can be initialized by providing an array initializer that lists the values of all elements:

new int[] {1, 2, 3} — allocate an int array containing the values 1, 2, and 3.

The value provided between the square brackets (if present) determines the length (of the given dimension) of the array:

new int[2] — allocates an int array with space for two elements (length 2), the elements are set to the default values (0), so this is equivalent to writing new int[] {0, 0}.

Thus, Java uses square brackets for array types, and to index into an array, but it uses curly braces to provide the list of element values at array initialization time.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.