10.3 One-Dimensional Arrays | 487
float[] angle; // Declares the array variable
angle = new float[4]; // Instantiates the array object
int[] testScore; // Declares the array variable
testScore = new int[10]; // Instantiates the array object
instantiate the arrays shown in Figure 10.3. Theanglear-
ray has four components, each capable of holding one
floatvalue. ThetestScorearray has a total of ten compo-
nents, all of typeint.
An array can be declared and instantiated in sepa-
rate statements or the declaration and creation can be
combined into one step as shown here.
// Declared and instantiated in one statement
float[] angle = new float[4];
// Declared and instantiated in one statement
int[] testScore = new int[10];
Because arrays are reference types in Java, they are in-
stantiated at run time, not at compile time. Therefore,
the Int-Expression used to instantiate an array object
does not have to be a constant. It can instead be a value
that you have read into the application. For example, if
you have read the value of dataSizefrom a file, the fol-
lowing declaration is legal:
int[] data = new int[dataSize];
Once instantiated, the array always has the specified number of components. For example,
if dataSizeis 10 when the array is instantiated but is later changed to 15,datastill has 10 com-
ponents.
Java provides an alternative syntax for declaring an array variable. You can place the
brackets that signal an array after the array name, as shown here:
charletters[];
charupperCase[];
charlowerCase[];
We do not recommend using this syntactic form, however. It is more consistent—and safer—
to place the brackets with the type of the components. It is safer because, as you may recall
from Chapter 2, Java also lets us declare multiple identifiers with a statement such as this:
charletters[], upperCase[], lowerCase;
testScore[ 0 ]
testScore[ 1 ]
testScore[ 2 ]
testScore[ 3 ]
testScore[ 4 ]
angle[ 0 ]
angle[ 1 ]
angle[ 2 ]
angle[ 3 ]
testScore[ 5 ]
testScore[ 6 ]
testScore[ 7 ]
testScore[ 8 ]
testScore[ 9 ]
angle testScore
Figure 10.3 angleand testScoreArrays