LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 9

Cloning a 2D array shares its rows Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 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[][] grid = {{1, 2}, {3, 4}};
        int[][] copy = grid.clone();
        copy[0][0] = 100;            // changes a shared row
        copy[1] = new int[]{9, 9};   // replaces a row only in the copy
        System.out.println(Arrays.deepToString(grid) + " " + Arrays.deepToString(copy));
    }
}
  • A [[100, 2], [3, 4]] [[100, 2], [9, 9]] Correct
  • B [[1, 2], [3, 4]] [[100, 2], [9, 9]]
  • C [[100, 2], [9, 9]] [[100, 2], [9, 9]]
  • D [[1, 2], [9, 9]] [[100, 2], [9, 9]]
Correct Answer: Option A

clone() copies the outer array of row references. Writing into a shared row affects both; replacing a row reference affects only the copy.

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