Java Reference
In-Depth Information
The following statement uses an array initializer to create a new array of length 5 and
initializes the ints with the values listed:
int [] amps = {5, 10, 20, 30, 50};
The value of amps[0] is 5 , amps[1] is 10 , and so on. Notice the semicolon at the end of
the line. It's a common mistake to forget it, but the compiler will gladly remind you if it is
missing!
You will definitely see array initializers on the exam, probably in several
questions. Some of the questions will be testing your knowledge of array
initializers, but expect to see array initializers on questions that are testing
your knowledge of some other exam objective.
If the array contains objects instead of primitives, you can use the new keyword in the
list of array elements. For example, the following statement creates an array referencing
three File objects:
File [] files = {new File(“input.txt”),
new File(“output.txt”),
new File(“error.txt”)};
The files array consists of three File references, with files[0] pointing to “input.
txt” , files[1] pointing to “output.txt” , and files[2] pointing to “error.txt” .
Notes on Array Initializers
To use the array initializer syntax, the array must be declared in the same statement that
declares the reference. For example, the following code generates a compiler error:
int [] amps;
amps = {5, 10, 20, 30, 50};
An array initializer can also be used to create a multidimensional array. For example, the
following statements create a two-dimensional array of fl oats:
float [][] results = {{2.0F, 1.5F},{-5.1F, 9.2F, 6.7F}};
The value of results[0][0] is 2.0 , results[1][0] is -5.1 , results[1][2] is 6.7 , and so on.
Search WWH ::




Custom Search