Java - Write code to add an empty item in the string array.

Requirements

Write code to add an empty item in the string array.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String[] array = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        System.out.println(java.util.Arrays
                .toString(addEmptyItemOnTop(array)));
    }//w  ww .  j a va  2  s . co  m

    /**
     * This method adds an empty item in the string array.
     * The content of the input array is assigned to the output array, not cloned.
     * @param array
     * @return
     */
    public static String[] addEmptyItemOnTop(String[] array) {
        String[] newArray;
        int i = 1;

        newArray = new String[array.length + 1];
        newArray[0] = "";
        for (String item : array) {
            newArray[i] = item;
            i++;
        }

        return newArray;
    }
}