Java Reference
In-Depth Information
This section introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
6.2.1 Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array and specify
the array's
element type
. Here is the syntax for declaring an array variable:
element type
elementType[] arrayRefVar;
The
elementType
can be any data type, and all elements in the array will have the same
data type. For example, the following code declares a variable
myList
that references an
array of double elements.
double
[] myList;
Note
You can also use
elementType arrayRefVar[]
to declare an array variable. This
style comes from the C language and was adopted in Java to accommodate C program-
mers. The style
elementType[] arrayRefVar
is preferred.
preferred syntax
6.2.2 Creating Arrays
Unlike declarations for primitive data type variables, the declaration of an array variable does not
allocate any space in memory for the array. It creates only a storage location for the reference to
an array. If a variable does not contain a reference to an array, the value of the variable is
null
.
You cannot assign elements to an array unless it has already been created. After an array variable
is declared, you can create an array by using the
new
operator with the following syntax:
null
arrayRefVar =
new
elementType[arraySize];
new
operator
This statement does two things: (1) it creates an array using
new elementType[array-
Size]
; (2) it assigns the reference of the newly created array to the variable
arrayRefVar
.
Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement as:
elementType[] arrayRefVar =
new
elementType[arraySize];
or
elementType arrayRefVar[] =
new
elementType[arraySize];
Here is an example of such a statement:
double
[] myList =
new double
[
10
];
This statement declares an array variable,
myList
, creates an array of ten elements of
double
type, and assigns its reference to
myList
. To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
For example, the following code initializes the array.
myList[
0
] =
5.6
;
myList[
1
] =
4.5
;
myList[
2
] =
3.3
;
myList[
3
] =
13.2
;