Java Arrays.copyOf() Example - Copying an Array

JavaArrays.copyOf() method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

If you want to copy the first few elements of an array or full copy of the array, you can use this method. Obviously, it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use. This method internally uses System arraycopy() method.

Java Arrays.copyOf() Example - Copying an Array

importjava.util.Arrays;/** * This class shows different methods for copy array in java *@author javaguides.net **/publicclassJavaArrayCopyExample {publicstaticvoidmain(String[]args) {int[] source= {1,2,3,4,5,6,7,8,9 };System.out.println("Source array ="+Arrays.toString(source));int[] dest=Arrays.copyOf(source, source.length);System.out.println("Copy First five elements of array. Result array ="+Arrays.toString(dest));       }}
Output:
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9]Copy First five elements of array. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Reference



Comments