Wanna Copy An Array in Java

Hi Friends
 

To copy an array in JAVA we have 3 options.

  • Manually iterating elements of the source array and placing each one into the destination array using a loop.
  • arraycopy() Method of java.lang.System class
Method syntax 
  1. public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)    
Demo Program
  1. class ArrayCopyDemo {  
  2.  public static void main(String[] args) {  
  3.   char[] copyFrom = {  
  4.    'd',  
  5.    'e',  
  6.    'c',  
  7.    'a',  
  8.    'f',  
  9.    'f',  
  10.    'e',  
  11.    'i',  
  12.    'n',  
  13.    'a',  
  14.    't',  
  15.    'e',  
  16.    'd'  
  17.   };  
  18.   char[] copyTo = new char[7];  
  19.   System.arraycopy(copyFrom, 2, copyTo, 07);  
  20.   System.out.println(new String(copyTo));  
  21.  }  
  22. }    
The output from this program is: caffein
  • copyOfRange() Method of java.util.Arrays class
Demo Program
  1. class ArrayCopyOfDemo {  
  2.  public static void main(String[] args) {  
  3.   char[] copyFrom = {  
  4.    'd',  
  5.    'e',  
  6.    'c',  
  7.    'a',  
  8.    'f',  
  9.    'f',  
  10.    'e',  
  11.    'i',  
  12.    'n',  
  13.    'a',  
  14.    't',  
  15.    'e',  
  16.    'd'  
  17.   };  
  18.   char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 29);  
  19.   System.out.println(new String(copyTo));  
  20.  }  
  21. }   
The output from this program is: caffein
 
The difference between the 2nd and 3rd is that using the copyOfRange method does not require you to create the destination array before calling the method because the destination array is returned by the method. Although it requires fewer lines of code.
 
Refer java docs by Oracle
 
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html