CodeGym/Java Blog/Java Arrays/Arrays.copyOf() Method in Java
Author
Vasyl Malik
Senior Java Developer at CodeGym

Arrays.copyOf() Method in Java

Published in the Java Arrays group
members

What is Arrays.copyOf() method in Java?

Java class java.util.Arrays provides a method called Arrays.copyOf() that returns a copy of an array passed as a parameter to this function, followed by specifying its size. Here’s the method header for quick understanding.
Arrays.copyOf(int[] templateArray, int length);
Note that the second parameter “length” is the size of the copy array you want to create. So here we can have 3 cases.
  • The lengths of both template & copy arrays are the same.
  • The length of the copy array is greater than the length of the template array.
  • The length of the copy array is lesser than the length of the template array.
Let’s look at the coding example to see how we can handle all three scenarios mentioned above. Arrays.copyOf() Method in Java - 1

Coding Example

import java.util.Arrays;
public class ArraysCopyOfMethod {
	public static void main(String[] args) {

	  // Initialize your templateArray which you want a copy of
        int[] templateArray = new int[] {1, 2, 3, 4, 5, 6};
        System.out.println("Template Array: " + Arrays.toString(templateArray));

        // Create a "copy" of template array using
        // Arrays.copyOf(int[] array, int arrayLength) method

        // CASE 1: Sizes of both template & copy arrays are same
        int[] copyArray1 = Arrays.copyOf(templateArray, templateArray.length);
        System.out.println("Copy Array 1: " + Arrays.toString(copyArray1));

        // CASE 2: Size of copy array > Size of template array
        // extra space in copy array is filled with zeros
        int[] copyArray2 = Arrays.copyOf(templateArray, 10);
        System.out.println("Copy Array 2: " + Arrays.toString(copyArray2));

        // CASE 3: Size of copy array < Size of template array
        // copy array is only filled with only elements in overlapping size
        int[] copyArray3 = Arrays.copyOf(templateArray, 3);
        System.out.println("Copy Array 3: " + Arrays.toString(copyArray3));
	}

}

Output

Template Array: [1, 2, 3, 4, 5, 6] Copy Array 1: [1, 2, 3, 4, 5, 6] Copy Array 2: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0] Copy Array 3: [1, 2, 3]

Conclusion

By now you must have a logical grasp over the Arrays.copyOf() method in Java. However, feel free to experiment with different inputs to fuel your curiosity.
Comments (1)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Faisal Ahmed
Level 13 , Bangalore, India
6 March 2023, 07:13
Copy Array 2: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0] Copy Array has four 0 values from index 6-9, If we wants to copy again few no. from Template array tp Copy Array to that particular index means, How can we do?