Consider the following code snippet:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i * 2;
}
System.out.println(numbers[3]);
}
}
What will be the output of the above code?
a) 0 b) 6 c) 3 d) 4
Explain your answer.
The correct answer is b) 6.
Explanation:
The code snippet declares and initializes an integer array numbers
with a size of 5 using the statement int[] numbers = new int[5];
.
The following for loop for (int i = 0; i < numbers.length; i++)
iterates through the array and assigns a value to each element using the expression numbers[i] = i * 2;
. This means the first element of the array will have a value of 0
, the second element will have 2
, the third element will have 4
, the fourth element will have 6
, and the fifth element will have 8
.
Finally, the code snippet prints the value of numbers[3]
using System.out.println(numbers[3]);
. Since array indices start from 0
, numbers[3]
corresponds to the fourth element of the array, which is 6
. Hence, the output will be 6
.