Wanna Copy An Array in Java

Hi Friends

To copy an array in JAVA we have 3 option.
  • Manually iterating elements of the source array and placing each one into the destination array using 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. {  
  3.     public static void main(String[] args)  
  4.     {  
  5.         char[] copyFrom =   
  6.         {  
  7.             'd''e''c''a''f''f''e',  
  8.                 'i''n''a''t''e''d'  
  9.         };  
  10.         char[] copyTo = new char[7];  
  11.   
  12.         System.arraycopy(copyFrom, 2, copyTo, 0, 7);  
  13.         System.out.println(new String(copyTo));  
  14.     }  
  15. }  
The output from this program is: caffein
  • copyOfRange() Method of java.util.Arrays class
Demo Program
  1. class ArrayCopyOfDemo  
  2. {  
  3.     public static void main(String[] args)  
  4.     {  
  5.   
  6.         char[] copyFrom =   
  7.         {  
  8.             'd''e''c''a''f''f''e',  
  9.                 'i''n''a''t''e''d'  
  10.         };  
  11.   
  12.         char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);  
  13.   
  14.         System.out.println(new String(copyTo));  
  15.     }  
  16. }  
The output from this program is: caffein

The difference between 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
Ebook Download
View all
Learn
View all