Method for String Building in java I have written a custom method to use StringBuilder in java. My Requirement is to create a method which accepts any number of arguments of any type and return String by concatenating the arguments.

eg. msgBuilder("Hello ",0," how"," are"," you ",2.5) return "Hello 0 how are you 2.5"

Here is my java code. Please Someone review my code and suggest If I did anything is wrong or Can I use this further in my projects.

        public class Test {
            public static void main(String[] args ){
                String msg = msgBuilder("Hello ",5," How ","are ","you");
                System.out.println(msg);
            }

            private static String msgBuilder(Object... params){
                StringBuilder sb = new StringBuilder();
                for(Object obj:params){
                    sb.append(obj);
                }
                return sb.toString();
            }
        }
Your approach

As pointed out by the other answers, you are practically hard-coding whitespaces in your arguments, which can get non-standard easily, even in your example. Otherwise, the use of StringBuilder is sound, although it wouldn't deal nicely with a single null value - the for-each loop will fail as it implicitly tries to get an Iterator for it.

Java 8

An alternative is to rely on the stream-based processing that Java 8 offers:

private static String format(Object... values) {
    if (values == null) {
        return "";
    }
    return Arrays.stream(values)
                    .map(Objects::toString)
                    .collect(Collectors.joining(" "));
}



Construct a Stream&lt;Object&gt; from values using Arrays.stream(T...). 
map() each value using Objects.toString(Object) as a method reference.
collect() the stream into a String by joining(" ") them together.