CodeBlanks Logo Icon CodeBlanks

Arrays.copyOf

Learn to copy with Arrays.copyOf.

Copying arrays: Arrays.copyOf

To take a copy of an array you use Arrays.copyOf. The first parameter is the source array, the second is the length of the new array.

int[] src = {1, 2, 3};
int[] copy = Arrays.copyOf(src, 3);
// copy: {1, 2, 3}

If the new length is smaller than the source, the array is truncated; if larger, the new slots are filled with the default value of the type (0 for int). The original array never changes.

Truncating and extending

By changing the second parameter you can truncate or extend the array. Truncating takes a portion from the start of the original; extending fills the extra slots with the default value.

int[] src = {10, 20, 30, 40};
int[] top2 = Arrays.copyOf(src, 2);
// top2: {10, 20}
int[] ext5 = Arrays.copyOf(src, 5);
// ext5: {10, 20, 30, 40, 0}

This is faster than building a new array from scratch, because the data is copied in one pass.

Practice Take a copy of the first three products

From the given 5 product codes, copy the first three with Arrays.copyOf and print the copy using Arrays.toString.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    int[] codes = {101, 102, 103, 104, 105};
    // Copy the first three codes
    // Print the copy
  }
}

Sample solution

Main.java
int[] top3 = Arrays.copyOf(codes, 3);
System.out.println(Arrays.toString(top3));

Expected output

[101, 102, 103]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Arrays.copyOf(src, 5) return when src has length 3?

Main.java
int[] src = {1, 2, 3};
int[] copy = Arrays.copyOf(src, 5);
  • An array of 5 elements; last 2 are 0
  • An array of 3 elements; length unchanged
  • An array of 5 elements; last 2 are null Correct answer
  • It throws an error; length exceeded

Explanation: Excess slots in an int array are filled with 0.

2 Fill in the blank: take a copy

Question
int[] src = {1, 2, 3};
int[] copy = Arrays.____(src, 3);
Answer
int[] src = {1, 2, 3};
int[] copy = Arrays.copyOf(src, 3);

Explanation: Arrays.copyOf(src, 3) returns a new array.

3 Match call to result

Term Meaning
copyOf(src, 2) Takes the first 2 elements
copyOf(src, 5) Fills extra with 0
copyOf(src, 0) Returns an empty array
copyOf(src, 3) Same length copy

All lessons in Beginner