How to Use Arrays.copyOf in Java: Syntax and Examples
Use
Arrays.copyOf(originalArray, newLength) to create a new array by copying elements from originalArray up to newLength. It returns a new array of the specified length, truncating or padding with default values if needed.Syntax
The Arrays.copyOf method has this syntax:
Arrays.copyOf(original, newLength)
Where:
- original: The array you want to copy.
- newLength: The length of the new array you want.
The method returns a new array of the same type as original, with elements copied up to newLength. If newLength is greater than the original array length, the extra elements are filled with default values (like 0 for int, null for objects).
java
int[] newArray = Arrays.copyOf(originalArray, newLength);
Example
This example shows how to copy an integer array to a new array with a different length using Arrays.copyOf. It prints both the original and copied arrays.
java
import java.util.Arrays; public class CopyOfExample { public static void main(String[] args) { int[] original = {1, 2, 3, 4, 5}; int[] copyShorter = Arrays.copyOf(original, 3); // copy first 3 elements int[] copyLonger = Arrays.copyOf(original, 7); // copy all + 2 default zeros System.out.println("Original array: " + Arrays.toString(original)); System.out.println("Copy with length 3: " + Arrays.toString(copyShorter)); System.out.println("Copy with length 7: " + Arrays.toString(copyLonger)); } }
Output
Original array: [1, 2, 3, 4, 5]
Copy with length 3: [1, 2, 3]
Copy with length 7: [1, 2, 3, 4, 5, 0, 0]
Common Pitfalls
Common mistakes when using Arrays.copyOf include:
- Using a
newLengthsmaller than zero, which throwsNegativeArraySizeException. - Expecting the original array to change (it does not;
copyOfreturns a new array). - Copying arrays of objects and forgetting that the copy is shallow (objects themselves are not cloned).
java
import java.util.Arrays; public class PitfallExample { public static void main(String[] args) { int[] original = {1, 2, 3}; // Wrong: negative length causes exception // int[] errorCopy = Arrays.copyOf(original, -1); // throws NegativeArraySizeException // Correct usage: int[] safeCopy = Arrays.copyOf(original, 5); System.out.println(Arrays.toString(safeCopy)); // prints [1, 2, 3, 0, 0] } }
Output
[1, 2, 3, 0, 0]
Quick Reference
Summary tips for Arrays.copyOf:
- Returns a new array with the specified length.
- If new length < original length, array is truncated.
- If new length > original length, extra elements are default values.
- Works with any array type (primitives or objects).
- Does not modify the original array.
Key Takeaways
Arrays.copyOf creates a new array by copying elements from the original up to the specified length.
If the new length is longer, extra elements are filled with default values like 0 or null.
The original array remains unchanged after copying.
Using a negative new length causes an exception.
Copying object arrays copies references, not deep clones.