Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Java Program to copy an array from the specified source array



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
Updated on: 2019-07-30T22:30:24+05:30

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements