Java Program to copy an array from the specified source array

Java 8Object Oriented ProgrammingProgramming

Use arraycopy() method in Java to copy an array from the specified source array.

Here, we have two arrays −

int arr1[] = { 10, 20, 30, 40};
int arr2[] = { 3, 7, 20, 30};

Now, we will use the arraycopy() method to copy the first two elements of the 1st array to the 2nd array −

System.arraycopy(arr1, 0, arr2, 2, 2);

The following is an example −

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      int arr1[] = { 10, 20, 30, 40};
      int arr2[] = { 3, 7, 20, 30};
      System.arraycopy(arr1, 0, arr2, 2, 2);
      System.out.print("New Array = ");
      System.out.print(arr2[0] + " ");
      System.out.print(arr2[1] + " ");
      System.out.print(arr2[2] + " ");
      System.out.print(arr2[3] + " ");
   }
}

Output

New Array = 3 7 10 20
raja
Published on 21-Dec-2018 11:21:54
Advertisements