Java Array append String to String array

Description

Java Array append String to String array


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] array = new String[] { "CSS", "HTML", "Java", null, "demo2s.com", "Javascript 123" };
        String str = "";
        System.out.println(java.util.Arrays.toString(addStringToArray(array, str)));
    }//w  w  w  .j  a  v a  2s  .c om

    /**
     * Append the given String to the given String array, returning a new array
     * consisting of the input array contents plus the given String.
     * 
     * @param array
     *            the array to append to (can be <code>null</code>)
     * @param str
     *            the String to append
     * @return the new array (never <code>null</code>)
     */
    public static String[] addStringToArray(String[] array, String str) {
        if (array == null || array.length < 0)
            return new String[] { str };
        String[] newArr = new String[array.length + 1];
        System.arraycopy(array, 0, newArr, 0, array.length);
        newArr[array.length] = str;
        return newArr;
    }
}



PreviousNext

Related