Java Reference
In-Depth Information
Java syntax: Array initializer
new type { expr 1 , ..., expr n }
Example : new int [] {3, 5, 2}
Example : int [] b = {3, 5, 2};
Purpose : Create an array with the elements given in the list.
In an initializing declaration, “ new type ” is not needed.
Instead, you can use an array initializer :
int [] c= new int [] {5, 6, 3, 4, 4};
The new-expression in this assignment creates an array whose size is the num-
ber of values in the list, assigns the given values to the array elements, and yields
as its value the name of the new array.
The next example illustrates two things. First, in an initializing declaration,
the part “ new type [] ” can be omitted. Second, arbitrary expressions can be used
as the expressions in an array initializer:
String[] s= {"Monday",
new String("Tuesday"),
"Wed" + "nesday"};
This creates a String array of three elements whose values are the strings
"Monday" , "Tuesday" , and "Wednesday" . (Of course, the second and third
expressions can be written more simply.)
You can omit “ new type [] ” only in an initializing declaration and not, for
example, in a simple assignment statement. Thus, the following is illegal:
c= {5, 6, 3, 4, 4}; // Illegal
Consequences of arrays as objects
Suppose we have two int [] variables b and c and a 4-element array:
b a0
c null
In this situation, we can create aliasing by executing this assignment:
c= b;
This stores in c the value that is in b :
Search WWH ::

Custom Search