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 the java.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:

  1.  Java throw and throws Keywords
  2. Java Stream map() vs flatMap() Method

2. Arrays.copyOf()

  • Arrays.copyOf() is a method provided by the java.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 the System.arraycopy()  method to perform the operation.

References

  1. Arrays.copyOf() – JavaDoc
  2. System.arraycopy()- JavaDoc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.