Array copy in java

The 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. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest.The number of components copied is equal to the length argument.

Example 1:

Input: arr1= [1,2,4]
Output: arr2=[1,2,4]

Approach: Array copy from one to another empty array

Java

import java.util.Arrays;

public class ArrayCopyDemo {
    public static void main(String[] args) {
        int arr1[] = { 124 };
        int arr2[] = new int[arr1.length];

        System.arraycopy(arr1, 0, arr2, 0arr1.length);
        System.out.print("array2 = " + Arrays.toString(arr2));
    }
}

Approach: Array copy from one to another array

Java


import java.util.Arrays;

public class ArrayCopyDemo {
    public static void main(String[] args) {
        int arr1[] = { 124 };
        int arr2[] = { 345600 };

        System.arraycopy(arr1, 0, arr2, 0arr1.length);
        System.out.print("array2 = " + Arrays.toString(arr2));
    }
}



No comments:

Post a Comment