Example of Arrays.copyOf and Arrays.copyOfRange in Java
May 18, 2013
Arrays.copyOf and Arrays.copyOfRange in Java are used to copy array from an array. The resulting array will be truncated array.
Arrays.copyOf accpets the original array and the length to truncate the array as an argument. It starts from zero index. If the length
is given greater than original array, the rest of the index is filled by zero. Arrays.copyOfRange accepts the original array and to and from
index to truncate the array.
CopyOfDemo.java
package com.util; import java.util.Arrays; public class CopyOfDemo { public static void main(String[] args) { int[] intArr={1,2,3,4,5}; int[] arr= Arrays.copyOf(intArr,2); System.out.println("value with Arrays.copyOf"); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } arr= Arrays.copyOfRange(intArr,1,3); System.out.println("\nvalue with Arrays.copyOfRange"); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } } }
value with Arrays.copyOf 1 2 value with Arrays.copyOfRange 2 3