Once the array is created, you can access an array element by using the name of the array followed by an index enclosed between a pair of square brackets. The index or subscript of an array indicates the position of an element in the array. The index of the first element in the array is always 0 (zero), the second element has an index 1 and so on. The index of the last element is always one less than the number of elements in the array. The syntax for accessing an array element is
arrayRefVar[index];
Here, index is an integer literal or an expression that evaluates to an into
In our example, the first element of the array is num[0],the second element is num[1] and the last element is num[4]
public class AccessingArrayElements
{
public static void main (String [] args)
{
int[] num = new int[5];
num[0] = 5;//Assigning value 5 to element at index 0
num[1] = 15;
num[2] = 25;
num[3] = 30;
num[4] = 50;
System.out.println("Array Element num[0] : " + num[0]);
System.out.println("Array Element num[1] : " + num[1]);
System.out.println("Array Element num[2] : " + num[2]);
System.out.println("Array Element num[3] : " + num[3]);
System.out.println("Array Element num[4] : " + num[4]);
}
}
Now let us consider another example that input the elements of an array and prints its contents.
import java.util.Scanner; //program uses Scanner class
public class ArrayElements
{
public static void main(String[] args)
{
int[] numArray = new int[5];
int i;
Scanner input=new Scanner(System.in);
System.out.print("Enter the 5 Array Elements : ");
for(i=0; i<5; i++)
numArray[i]=input.nextInt(); //Read number
for(i=0; i<numArray.length; i++)
System.out.println("Array element[" + i + "] : " +numArray[i]);
}
}
This example inputs an array and prints its contents.
The statement,
int[] numArray = new int[5];
creates a numArray array variable that references an int-array containing 5 elements. We create a Scanner object to obtain an input from the keyboard. Finally, when all the input has been made it is printed.