System.arraycopy() vs. Arrays.copyOf() in Java
In Java, both Arrays.copyOf()
and System.arraycopy()
are methods used to copy elements from one array to another. But, they are significantly different in their usage and behavior.
1. System.arraycopy()
System.arraycopy()
is a method provided by thejava.lang.System
class.- It copies a range of elements from the source array to a specified position in the destination array.
- It allows you to specify the source array, the starting index in the source array, the destination array, the starting index in the destination array, and the number of elements to be copied.
- It does not create a new array but modifies the existing one.
Here’s an example:
int[] sourceArray = {1, 2, 3, 4, 5};
int[] newArray = new int[3];
System.arraycopy(sourceArray, 0, newArray, 0, 3);
System.out.println(Arrays.toString(newArray)); // Output: [1, 2, 3]
Similar Posts:
2. Arrays.copyOf()
Arrays.copyOf()
is a method provided by thejava.util.Arrays
class.- It creates a new array and copies the specified elements from the source array into the new array.
- It allows you to specify the length of the new array explicitly.
- If the specified length is greater than the length of the source array, the new array will be padded with default values (0 for numeric types,
null
for reference types).
Let’s have a look at the below code snippet:
int[] sourceArray = {1, 2, 3, 4, 5};
int[] newArray = Arrays.copyOf(sourceArray, 3);
System.out.println(Arrays.toString(newArray)); // Output: [1, 2, 3]
In short, Arrays.copyOf()
creates a new array of a specified length and copies elements from the source array, while System.arraycopy()
copies a range of elements from the source array to a specified position in the destination array.
P.S.
Arrays.copyOf()
internally usages theSystem.arraycopy()
method to perform the operation.