Java - Write code to Join all of the strings in arr into one String with separator added between each element.

Requirements

Write code to Join all of the strings in arr into one String with separator added between each element.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String[] arr = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        String separator = "|";
        System.out.println(join(arr, separator));
    }//from  ww  w.  ja v  a 2s .  c o  m

    /**
     * Joins all of the strings in arr into one String with separator added
     * between each element.
     */
    public static String join(final String[] arr, final String separator) {
        if (arr.length < 2)
            return (arr.length == 1 ? arr[0] : "");
        final StringBuffer sb = new StringBuffer(arr[0]);
        for (int i = 1; i < arr.length; ++i) {
            sb.append(separator);
            sb.append(arr[i]);
        }
        return sb.toString();
    }
}

Related Exercise