LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 14

Arrays.fill on a 2D array Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links