System Arraycopy

Hey guys!! Welcome to flower brackets blog. System arraycopy example gives us the insight of how java arraycopy works in java.

System Arraycopy

java.lang.System.arraycopy() method copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

This method provide useful methods for standard input and output and for loading files and libraries.

A subsequence of array components are copied from the source array referenced by source to the destination array referenced by destination.

Declaration

public static void arraycopy(Object source, int sourcePosition, 
Object destination, int destinationPosition, int length)

Parameters: 

source : source array to be copied from.
sourcePosition : starting position in the source array.
destination : destination array.
destinationPosition : starting position in destination array.
length : total number of components to be copied.

This method does not return any value.

Example

public class ArrayCopyDemo
{
   public static void main(String[] args)
   {
      int arrOne[] = {2,4,6,8,10,12,14,16,18,20}; 
      int arrTwo[] = {1,3,5,7,9,11,13,15,17,19}; 

      int sourceArr[], sourcePosition, destinationArr[], destinationPosition, len; 
      sourceArr = arrOne; 
      sourcePosition = 2; 
      destinationArr = arrTwo; 
      destinationPosition = 5; 
      len = 4; 

      // printing elements of source array 
      System.out.print("Source array : "); 
      for(int a = 0; a < arrOne.length; a++) 
         System.out.print(arrOne[a] + " "); 
      System.out.println(""); 

      System.out.println("sourcePosition : " + sourcePosition); 

      // print elements of destination array 
      System.out.print("Destination array : "); 
      for(int a = 0; a < arrTwo.length; a++) 
         System.out.print(arrTwo[a] + " "); 
      System.out.println(""); 

      System.out.println("destinationPosition : " + destinationPosition); 

      System.out.println("Length : " + len); 

      // using ArrayCopy() method 
      System.arraycopy(sourceArr, sourcePosition, destinationArr, destinationPosition, len); 

      // printing final array 
      System.out.print("Final array : "); 
      for(int a = 0; a < arrTwo.length; a++) 
         System.out.print(arrTwo[a] + " ");
   }
}

Output:

Source array : 2 4 6 8 10 12 14 16 18 20
sourcePosition : 2
Destination array : 1 3 5 7 9 11 13 15 17 19
destinationPosition : 5
Length : 4
Final array : 1 3 5 7 9 6 8 10 12 19


Related Posts