Java Reference
In-Depth Information
Figure 9.1
Output of the ArrayDemo program.
Array Initializers
In Java, you can declare an array reference, instantiate an array, and fill the
array with elements all in a single statement. This process, which is referred to
as an array initializer , is useful when creating small arrays that contain prede-
termined data.
An array initializer creates an array without using the new keyword. The
elements in the array are listed within curly braces, separated by commas. For
example, the following array initializer creates an array of five ints:
int [] odds = {1, 3, 5, 7, 9};
The first element in the odds array is 1, the second element is 3, and so on.
Note that a semicolon is required after the right curly brace.
The following ArrayInitDemo program demonstrates array initializers.
Study the program and try to determine its output, which is shown in Figure
9.2.
public class ArrayInitDemo
{
public static void main(String [] args)
{
int [] odds = {1, 3, 5, 7, 9};
System.out.println(“odds.length = “ + odds.length);
for(int i = 0; i < odds.length; i++)
Search WWH ::




Custom Search