Oracle Certified Associate Java Se 8 Programmer · Free Practice Question Hard
Question 23
What will be the result of compiling and executing Test class?
- package com.udayan.oca;
- public class Test {
- public static void main(String[] args) {
- int [] arr = {3, 2, 1};
- for(int i : arr) {
- System.out.println(arr[i]);
- }
- }
- }
-
A
Compilation error
-
B
1
2
3 -
C
3
2
1 -
D
ArrayIndexOutOfBoundsException is thrown at runtime
Reveal correct answer
Correct answer: D
Explanation
Inside enhanced for loop, System.out.println(arr[i]); is used instead of System.out.println(i);
When loop executes 1st time, i stores the first array element, which is 3 but System.out.println statement prints arr[3] and this causes java runtime to throw the instance of ArrayIndexOutOfBoundsException.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
