How to merge two arrays in Java

How to merge two arrays in Java.

package codsstore;

/**
 * @author Sameera Jayasekara
 */

public class MergeArray {

    public static void main(String[] args) {

        String[] arr1 = {"sam", "jay", "nimal"};
        String[] arr2 = {"nick", "sanjay", "amila", "sanath"};
        String[] arr3 = new String[arr1.length + arr2.length];

        System.arraycopy(arr1, 0, arr3, 0, arr1.length);
        System.arraycopy(arr2, 0, arr3, arr1.length, arr2.length);

        for (String s : arr3) {
            System.out.println(s);
        }
    }
}
Output:
sam
jay
nimal
nick
sanjay
amila
sanath

No comments:

Post a Comment