Java Reference
In-Depth Information
An index must be a nonnegative integer . A program can use an expression as an index.
For example, if we assume that variable a is 5 and variable b is 6 , then the statement
c[a + b] += 2 ;
adds 2 to array element c[11] . An indexed array name is an array-access expression , which
can be used on the left side of an assignment to place a new value into an array element.
Common Programming Error 7.1
An index must be an int value or a value of a type that can be promoted to int —namely,
byte , short or char , but not long ; otherwise, a compilation error occurs.
Let's examine array c in Fig. 7.1 more closely. The name of the array is c . Every array
object knows its own length and stores it in a length instance variable . The expression
c.length returns array c 's length. Even though the length instance variable of an array is
public , it cannot be changed because it's a final variable. This array's 12 elements are
referred to as c[0] , c[1] , c[2] , …, c[11] . The value of c[0] is -45 , the value of c[1] is
6 , the value of c[2] is 0 , the value of c[7] is 62 and the value of c[11] is 78 . To calculate
the sum of the values contained in the first three elements of array c and store the result
in variable sum , we would write
sum = c[ 0 ] + c[ 1 ] + c[ 2 ];
To divide the value of c[6] by 2 and assign the result to the variable x , we would write
x = c[ 6 ] / 2 ;
7.3 Declaring and Creating Arrays
Array objects occupy space in memory. Like other objects, arrays are created with keyword
new . To create an array object, you specify the type of the array elements and the number
of elements as part of an array-creation expression that uses keyword new . Such an expres-
sion returns a reference that can be stored in an array variable. The following declaration
and array-creation expression create an array object containing 12 int elements and store
the array's reference in the array variable named c :
int [] c = new int [ 12 ];
This expression can be used to create the array in Fig. 7.1. When an array is created, each
of its elements receives a default value—zero for the numeric primitive-type elements,
false for boolean elements and null for references. As you'll soon see, you can provide
nondefault element values when you create an array.
Creating the array in Fig. 7.1 can also be performed in two steps as follows:
int [] c; // declare the array variable
c = new int [ 12 ]; // create the array; assign to array variable
In the declaration, the square brackets following the type indicate that c is a variable that
will refer to an array (i.e., the variable will store an array reference ). In the assignment state-
ment, the array variable c receives the reference to a new array of 12 int elements.
Common Programming Error 7.2
In an array declaration, specifying the number of elements in the square brackets of the
declaration (e.g., int[12] c ; ) is a syntax error.
 
 
Search WWH ::




Custom Search