VOOZH about

URL: https://www.geeksforgeeks.org/java/arrays-copyof-in-java-with-examples/

⇱ Arrays copyOf() in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Arrays copyOf() in Java with Examples

Last Updated : 23 Jul, 2025

Arrays.copyOf() is a method of java.util.Arrays class. It is used to copy the specified array, truncating or padding with false (for boolean arrays) if necessary so that the copy has the specified length.

This method can be used with both 1D and 2D arrays, but it’s important to note that Arrays.copyOf() performs a shallow copy, meaning that if you’re copying an array of objects, the objects themselves are not duplicated—only the references to them.

Example:

The below example shows the basic use of Arrays.copyOf() method to create a copy of an array with a specified length.


Output
Original Array: [1, 2, 3, 4, 5]
Copied Array: [1, 2, 3, 4, 5]

This demonstrates how Arrays.copyOf() method can be used to duplicate a 1D array with basic functionality before exploring complex examples.

Copying 1D Arrays

Here, we will learn how to use Arrays.copyOf() method to copy a 1D array and then modify its extra elements.

Syntax to Copy 1D Array

Arrays.copyOf(int [] original, int newLength);

  • original: The original array to be copied.
  • newLength: The desired length of the new copy.

Example of Copying 1D Array


Output
Original Array:
1 2 3 

Copied array after modifications:
1 2 3 4 5 

Copying 1D Array with a Larger Length

When the length of the copied array is greater than the original, the new array is padded with default values (0 for int, false for boolean, and null for reference types) to fill the remaining indices.

Example:


Output
Original Array:
1 2 3 
New array of higher length:
1 2 3 0 0 

Copying 2D Arrays

When working with 2D arrays, the Arrays.copyOf() method performs a shallow copy, meaning only the references to each row are copied. For a deep copy of the rows in a 2D array, you would need to copy each row individually.

Syntax to Copy 2D Array

Arrays.copyOf(originalArray, newLength);

Example of Copying 2D Array


Output
Original Array:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Copied Array:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Comment