Java Reference
In-Depth Information
Like any other primitive data type variable, an array can also be initialized with specific
values when it is declared. For example, the following Java statement declares an array,
sales
, of five elements and initializes those elements to specific values:
double
[] sales = {12.25, 32.50, 16.90, 23, 45.68};
The initializer list contains values, called initial values, that are placed between braces
and separated by commas. Here,
sales[0] = 12.25
,
sales[1] = 32.50
,
sales[2] =
16.90
,
sales[3] = 23.00
, and
sales[4]= 45.68
.
Note the following about declaring and initializing arrays:
When declaring and initializing arrays, the size of the array is determined
by the number of initial values in the initializer list within the braces.
If an array is declared and initialized simultaneously, we do not use the
operator
new
to instantiate the array object.
Recall that an array is an object; therefore, to store data, the array object must be
instantiated. Associated with each array that has been instantiated (that is, for which
memory has been allocated to store data), there is a
public
(
final
) instance variable
length
. The variable
length
contains the size of the array. Because
length
is a
public
member, it can be directly accessed in a program using the array name and the dot
operator.
Consider the following declaration:
int
[] list = {10, 20, 30, 40, 50, 60};
This statement creates the array
list
of six elements and initializes the elements using the
values given. Here,
list.length
is
6
.
Consider the following statement:
int
[] numList =
new int
[10];
This statement creates the array
numList
of
10
elements and initializes each element to
0
.
Because the number of elements of
numList
is
10
, the value of
numList.length
is
10
.
Now consider the following statements:
numList[0] = 5;
numList[1] = 10;
numList[2] = 15;
numList[3] = 20;
These statements store
5
,
10
,
15
, and
20
, respectively, in the first four elements of
numList
. Even though we put data into only the first four elements, the value of
numList.length
is
10
, the total number of array elements.
Search WWH ::
Custom Search