Which of the following code gives error of “out of bounds” in array?
2024
Which of the following code gives error of “out of bounds” in array?
- A.
int[] a = new int[5];
a[4] = 5; - B.
int[] a = {1, 2, 3, 4, 5};
System.out.print(a[2]); - C.
int[] a = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = i * 2;
} - D.
int[] a = new int[3];
a[3] = 9; - E.
Question not attempted
Attempted by 163 students.
Show answer & explanation
Correct answer: D
To determine which code gives an "out of bounds" error, we need to check if any array index accessed is outside the valid range (0 to length-1).
Option A: int[] a = new int[5]; a[4] = 5;
Step 1: Array a has size 5, so valid indices are 0, 1, 2, 3, 4.
Step 2: a[4] accesses the last valid index.
Step 3: This is within bounds, so no out of bounds error.
Option B: int[] a = {1, 2, 3, 4, 5}; System.out.print(a[2]);
Step 1: Array a has size 5, valid indices 0 to 4.
Step 2: a[2] accesses index 2, which is valid.
Step 3: No out of bounds error occurs.
Option C: int[] a = new int[10]; for (int i = 0; i < a.length; i++) { a[i] = i * 2; }
Step 1: Array a has size 10, valid indices 0 to 9.
Step 2: Loop runs from i = 0 to i < 10, so i takes values 0 to 9.
Step 3: a[i] accesses valid indices, so no out of bounds error.
Option D: int[] a = new int[3]; a[3] = 9;
Step 1: Array a has size 3, valid indices 0, 1, 2.
Step 2: a[3] attempts to access index 3, which is beyond the last valid index.
Step 3: This causes an out of bounds error.