Java tips on joining string with separator

This is Java tips on joining string with separator. Sometimes you have an Array or List and you want to join the String with separator. For example, an Array {“one”,”two”,”three”}, you want to make it as a String as “one,two,three”.

You can have several ways, here do two:

private static String join_1(String[] array, String separator) {
	String s = "";
	String comma = "";
	for(int i = 0; i < array.length; i++) {
		s = s + comma + array[i];
		comma = separator;
	}
	return s;
}

private static String join_2(String[] array, String separator) {
	String s = "";
	for(int i = 0; i < array.length; i++) {
		s = s + array[i] + separator;
	}
	return s.substring(0, s.length() - separator.length());
}

I will recommend first method. Here is my analysis.

Both code run in same speed. Test by putting 10000 elements of array.

First code will simply lesser memory consumption compared to second code. As String#substring will create another new copy of String with different offset.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

1 thought on “Java tips on joining string with separator”

Leave a Reply