Question 14
Back to Exercise
What is the output of the following Java program?
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] row = new int[3];
int[][] grid = new int[2][];
Arrays.fill(grid, row); // both slots point to the SAME row array
grid[0][1] = 5;
int[][] good = new int[2][3];
for (int[] r : good) Arrays.fill(r, 7);
good[0][1] = 5;
System.out.println(Arrays.deepToString(grid) + " " + Arrays.deepToString(good));
}
}
- A [[0, 5, 0], [0, 5, 0]] [[7, 5, 7], [7, 7, 7]] Correct
- B [[0, 5, 0], [0, 0, 0]] [[7, 5, 7], [7, 7, 7]]
- C [[0, 5, 0], [0, 5, 0]] [[7, 5, 7], [7, 5, 7]]
- D NullPointerException
Correct Answer: Option A
Filling an array of references stores the same reference in every slot. Fill each row separately instead.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!