LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 10

Arrays.copyOf growing and shrinking Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 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) {
        String[] s = {"x", "y", "z"};
        System.out.println(Arrays.toString(Arrays.copyOf(s, 5)));
        System.out.println(Arrays.toString(Arrays.copyOf(s, 2)));
        int[] n = {4, 5, 6};
        System.out.println(Arrays.toString(Arrays.copyOfRange(n, 1, 5)));
    }
}
  • A [x, y, z, null, null] [x, y] [5, 6, 0, 0] Correct
  • B [x, y, z, , ] [x, y] [5, 6]
  • C [x, y, z] [x, y] [5, 6, 0, 0]
  • D ArrayIndexOutOfBoundsException
Correct Answer: Option A

Extra positions get default values; copyOfRange may extend past the end, padding with defaults too.

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