Java Reference
In-Depth Information
Java syntax: Array type
type []
Example : int []
Meaning : type [] is the type of an array
whose elements are of type type .
Java syntax: new-array expression
new type [ int - expression ]
Example : new double [15]
Purpose : Evaluation creates an array object
with expression elements, all of type type , and
has as its value the name of the object.
Execution of this statement proceeds as follows:
1. Evaluate the new-expression: create an array of 4 int variables, give it a
name (e.g. a0 ), and yield as the result of the expression the name ( a0 ).
2. Store the name a0 in array variable b .
Once the array has been created, its size cannot be changed, so you have to
figure out how many elements it should have before creating it.
You can combine declaration and initialization in an initializing declaration:
int [] b= new int [4];
Referencing the length of an array
Every array object has a fixed field length , which contains the number of ele-
ments in the array. Thus, if b is an array variable, the expression:
is the number of elements in, or length of, array b . Note that length is a variable
and not a function, so no parentheses appear after it.
The loop below sets all the elements of array b to 72 :
// inv: elements b[0..i-1] have been set to 72
for ( int i= 0; i != b.length; i= i+1) {
b[i]= 72;
8-1.3 shows
execution of
such a loop
Array initializers
The following sequence of statements creates an array c that contains the values
5 , 6 , 3 , 4 , and 4 , but it is rather cumbersome:
int [] c= new int [5];
c[0]= 5; c[1]= 6; c[2]= 3; c[3]= 4; c[4]= 4;
Programming tip: Rather than typing 4 for the array size throughout your program, use
b.length . That way, if you decide to change the size of the array, you need to
make changes in only one place, where the array is created.
Search WWH ::

Custom Search