LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 2

Changing an array through an alias Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 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[] a = {1, 2, 3};
        int[] b = a;
        int[] c = a.clone();
        b[0] = 10;
        c[1] = 20;
        System.out.println(Arrays.toString(a) + " " + Arrays.toString(b) + " " + Arrays.toString(c));
    }
}
  • A [10, 2, 3] [10, 2, 3] [1, 20, 3] Correct
  • B [1, 2, 3] [10, 2, 3] [1, 20, 3]
  • C [10, 20, 3] [10, 20, 3] [10, 20, 3]
  • D [10, 2, 3] [10, 2, 3] [10, 20, 3]
Correct Answer: Option A

b is the same array as a; c is an independent copy made before the changes.

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