LearnFrenzy
Sign in Take a free test

Object Class and Wrapper Classes · Predict the Output · Question 6

Cloning an array of arrays Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 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[] flat = {1, 2, 3};
        int[][] grid = {{1, 2}, {3, 4}};
        int[] flatCopy = flat.clone();
        int[][] gridCopy = grid.clone();
        flatCopy[0] = 99;
        gridCopy[0][0] = 99;
        System.out.println(Arrays.toString(flat) + " " + Arrays.deepToString(grid) + " " + (grid[1] == gridCopy[1]));
    }
}
  • A [1, 2, 3] [[99, 2], [3, 4]] true Correct
  • B [99, 2, 3] [[99, 2], [3, 4]] true
  • C [1, 2, 3] [[1, 2], [3, 4]] false
  • D [1, 2, 3] [[99, 2], [3, 4]] false
Correct Answer: Option A

Array clone() is shallow: the copy of grid holds the same inner arrays.

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