Java Reference
In-Depth Information
Declaring and Creating an Array
You declare an array name and create an array in almost the same way that you create and
name objects of classes. There is only a slight difference in the syntax.
SYNTAX
Base_Type [] Array_Name = new Base_Type [ Length ];
The Length may be given as any expression that evaluates to a nonnegative integer. In partic-
ular Length can be an int variable.
EXAMPLES
char [] line = new char [80];
double [] reading = new double [300];
Person[] specimen = new Person[100];
Person is a class.
Instead of writing an integer constant in the square brackets, you can use any expres-
sion that evaluates to an integer that is at least
and at most
4 . So, the following is
0
allowed:
System.out.println(score[index] + " is at position " + index);
where index is a variable of type int that has been given one of the values 0 , 1 , 2 , 3 , or 4 .
When we refer to these indexed variables grouped together into one collective
item, we will call them an array. So, we can refer to the array named score (without
using any square brackets).
The program in Display 6.1 shows an example of using our sample array score as
five indexed variables, all of type double .
Note that the program can compute the name of an indexed variable by using a
variable as the index, as in the following for loop:
for (index = 0; index < 5; index++)
System.out.println(score[index] + " differs from max by "
+ (max
score[index]));
Do not confuse the three ways to use the square brackets [] with an array name.
First, the square brackets can be used to create a type name, such as the double[] in
the following:
square
brackets []
double [] score;
Second, the square brackets can be used with an integer value as part of the special
syntax Java uses to create a new array, as in
score = new double [5];
Search WWH ::




Custom Search