Menu
Topics Index
...
`

Student Marks Array - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App