Java Reference
In-Depth Information
// Call another method with an anonymous array (of anonymous objects)
double d = computeAreaOfTriangle ( new Point [] { new Point ( 1 , 2 ),
new Point ( 3 , 4 ),
new Point ( 3 , 2 ) });
When an array initializer is part of a variable declaration, you may omit the new
keyword and element type and list the desired array elements within curly braces:
String [] greetings = { "Hello" , "Hi" , "Howdy" };
int [] powersOfTwo = { 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 };
Array literals are created and initialized when the program is run, not when the pro‐
gram is compiled. Consider the following array literal:
int [] perfectNumbers = { 6 , 28 };
This is compiled into Java byte codes that are equivalent to:
int [] perfectNumbers = new int [ 2 ];
perfectNumbers [ 0 ] = 6 ;
perfectNumbers [ 1 ] = 28 ;
The fact that Java does all array initialization at runtime has an important corollary.
It means that the expressions in an array initializer may be computed at runtime
and need not be compile-time constants. For example:
Point [] points = { circle1 . getCenterPoint (), circle2 . getCenterPoint () };
Using Arrays
Once an array has been created, you are ready to start using it. The following sec‐
tions explain basic access to the elements of an array and cover common idioms of
array usage such as iterating through the elements of an array and copying an array
or part of an array.
Accessing array elements
The elements of an array are variables. When an array element appears in an expres‐
sion, it evaluates to the value held in the element. And when an array element
appears on the left-hand side of an assignment operator, a new value is stored into
that element. Unlike a normal variable, however, an array element has no name,
only a number. Array elements are accessed using a square bracket notation. If a is
an expression that evaluates to an array reference, you index that array and refer to
a specific element with a[i] , where i is an integer literal or an expression that eval‐
uates to an int . For example:
// Create an array of two strings
String [] responses = new String [ 2 ];
responses [ 0 ] = "Yes" ; // Set the first element of the array
responses [ 1 ] = "No" ; // Set the second element of the array
// Now read these array elements
Search WWH ::




Custom Search