Java - Write code to Append the second string array to the first one.

Requirements

Write code to Append the second string array to the first one.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String[] firstArray = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        String[] secondArray = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        System.out.println(java.util.Arrays.toString(append(firstArray,
                secondArray)));/*from  w  w  w  .  jav  a2  s.c  o  m*/
    }

    /**
     * Appends the second string array to the first one. This is a costly operation as all array members
     * are copied to the result string array.
     *
     * @param firstArray Specifies a string array.
     * @param secondArray Specifies the string array to be appended.
     * @return Returns the new combined string array.
     */
    public static String[] append(String[] firstArray, String[] secondArray) {
        if (firstArray == null)
            return (secondArray);

        if (secondArray == null)
            return (firstArray);

        String[] result = new String[firstArray.length + secondArray.length];
        int index;
        for (index = 0; index < firstArray.length; ++index)
            result[index] = firstArray[index];

        for (index = 0; index < secondArray.length; ++index)
            result[index + firstArray.length] = secondArray[index];

        return (result);
    }
}

Related Exercise