Java Code to Copy Array into Another Array

1. Using Custom Method

import java.util.Arrays;

public class ArrayCopy {

    public static void main(String args[]) {
        String[] myStringArray = { "Alice", "Bob", "Tim", "John", "Denice" };
        System.out.println("Array " + Arrays.toString(myStringArray));
        String[] newStringArray = copyArray(myStringArray);
        System.out.println("Copied Array " + Arrays.toString(newStringArray));
    }

     public static String[] copyArray(String[] stringArray) {
        String[] newStringArray = new String[stringArray.length];
        for (int i = 0; i < stringArray.length; i++) {
             newStringArray[i] = stringArray[i];
        }
        return newStringArray;
     }

}

2. Using copyOf method in java.util.Arrays package.

public class ArrayCopy {

    public static void main(String args[]) {
        String[] myStringArray = { "Alice", "Bob", "Tim", "John", "Denice" };
        System.out.println("Array " + Arrays.toString(myStringArray));
        String[] newStringArray = Arrays.copyOf(myStringArray, myStringArray.length);
        System.out.println("Copied Array " + Arrays.toString(newStringArray));
    }

}
tgugnani: Web Stuff Enthusiast.