add String Element to String array - Java java.lang

Java examples for java.lang:String Array

Description

add String Element to String array

Demo Code


//package com.java2s;
import java.util.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] elements = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        String addString = "java2s.com";
        System.out.println(java.util.Arrays.toString(addStringElement(
                elements, addString)));//from w  w w .  ja v a  2 s. c o  m
    }

    public static String[] addStringElement(String[] elements,
            String addString) {
        // Local variables
        String[] newStringArray;
        // Check if the supplied String array is null and if so, we will be
        // adding one element
        if (elements != null) {
            // Supplied array contains elements so the new size will be
            // increased by 1 and add element
            newStringArray = Arrays.copyOf(elements, elements.length + 1);
            // Set the last element to supplied String addString
            newStringArray[elements.length] = addString;
        } else {
            // Supplied array does not contain any elements yet
            newStringArray = new String[1];
            // Set the first/last and only element to supplied String addString
            newStringArray[0] = addString;
        }
        return newStringArray;
    }
}

Related Tutorials