Menu
Topics Index
...
`


Array - Overview >
Siva Nookala - 11 Apr 2016
Since array contains multiple elements, but we have only one variable, we use index to access the elements. The index is nothing but an unique number which identifies each element. Using the index, the element at that index can be initialized or can be read.

  • The index has to be specified within square brackets and all array indexes start at zero. The index of first element is zero, second element is 1 etc., So, for accessing fifth element in an array student_marks, you need to use
    student_marks[4] = 87;
    The fifth element is accessed using index four (4). Similarly tenth element is accessed using index 9 and 8th element is accessed using 7.
Array-indices
  • For an array of size N, the valid indices are 0, 1, 2 ..., N-2, N-1. For array with size 4, the valid indices are 0, 1, 2, 3. If any other index is used to access the element then ArrayIndexOutOfBoundsException will be thrown.
Student Marks Array
class StudentMarksArray
{
    public static void main(String arg[])
    {
        int student_marks[] = new int[5];
        student_marks[2] = 25; // LINE A
        System.out.println("Third Element = " + student_marks[2]); // LINE B
        System.out.println("Fourth Element = " + student_marks[3]); // LINE C
        
        // student_marks[-3] = 45; // Won't work // LINE D
        // student_marks[5] = 32; // Won't work // LINE E
    
    }
}
OUTPUT

Third Element = 25
Fourth Element = 0

DESCRIPTION

In LINE A, we are assigning 25 to the third element i.e. index 2. In LINE B, we are printing third element i.e. also index 2. So it will print the previously assigned value, which is 25. In LINE C, we are printing fourth element i.e. index 3. Since it was not assigned previously, the original default value of 0 is printed.

THINGS TO TRY
  • Uncomment LINE D - to see the ArrayIndexOutOfBoundsException
  • Similarly uncomment LINE E - to see the ArrayIndexOutOfBoundsException.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.