by Dinesh Thakur Category: array

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


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]);

Accessing Array Elements in Java

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

Accessing Array Elements in Java with Example

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.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles