next up previous
Next: Example: sum of the Up: Unit 07 Previous: Number of elements of

Expressions that denote array objects

In Java, it is possible to write expressions that denote array objects, similarly to what we have seen for strings, where, e.g., "ciao" denotes a String object. An expression that denotes an array object is a list of expressions, of the type of the elements of the array, of the form:

{ expression1, expression2, ..., expressionk }
and it denotes an array object of k elements.

Example:

int[] v = { 4, 6, 3, 1 };
is equivalent to:
int[] v = new int[4];
v[0] = 4; v[1] = 6; v[2] = 3; v[3] = 1;

Note: While a literal of type String, such as "ciao" can be used anywhere in the body of a method to denote a string object, the expressions that denote an array can be used only to initialize an array when it is declared. The following example shows a fragment of code that is wrong:

int[] v;
v = { 4, 6, 3, 1 };  // ERROR!


next up previous
Next: Example: sum of the Up: Unit 07 Previous: Number of elements of