Java - Array Elements Accessing

Introduction

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.

The index is zero-based.

The index for the last element of an array is the length of the array minus 1.

Example

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].

P:It is a runtime error to refer to a non-existing element of an array.

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

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

You can use the following loop to access array elements

for (int i = 0 ; i < empId.length; i++) {
        empId[i] = (i + 1) * 10;
}

Related Topics

Quiz

Exercise