Java Reference
In-Depth Information
Accessing Array Elements
Once you create an array object using the
new
operator, you can refer to each individual element of the array using an
element's index enclosed in brackets. The index for the first element is 0, the second element 1, the third element 2, and
so on. This is called zero-based indexing. The index for the last element of an array is the length of the array minus 1. If you
have an array of length 5, the indexes of the array elements would be 0, 1, 2, 3, and 4. Consider the following statement:
int[] empId = new int[5];
The length of the
empId
array is 5; its elements can be referred to as
empId[0]
,
empId[1], empId[2]
,
empId[3]
,
and
empId[4]
.
It is a runtime error to refer to a non-existing element of an array. For example, using
empId[5]
in your code will
throw an exception, because
empId
has a length of 5 and
empId[5]
refers to the sixth element, which is non-existent.
You can assign values to elements of an array as follows:
empId[0] = 10; // Assign 10 to the first element of empId
empId[1] = 20; // Assign 20 to the second element of empId
empId[2] = 30; // Assign 30 to the third element of empId
empId[3] = 40; // Assign 40 to the fourth element of empId
empId[4] = 50; // Assign 50 to the fifth element of empId
Table
15-1
shows the details of an array. It shows the indexes, values, and references of the elements of the array
after the above statements are executed.
Table 15-1.
Array Elements in Memory for the empId Array
0
1
2
3
4
Element's Index
10
20
30
40
50
Element's Value
empId[0]
empId[1]
empId[2]
empId[3]
empId[4]
Element's Reference
The following statement assigns the value of the third element of the
empId
array to an
int
variable
temp
:
int temp = empId[2]; // Assigns 30 to temp
Length of an Array
An array object has a
public final
instance variable named
length
, which contains the number of elements in the array.
int[] empId = new int[5]; // Create an array of length 5
int len = empId.length; // 5 will be assigned to len
Note that
length
is the property of the array object you create. Until you create the array object, you cannot use
its
length
property. The following code fragment illustrates this:
// salary is a reference variable, which can refer to an array of int.
// At this point, it is not referring to any array object.
int[] salary;