Princeyesuraj Princeyesuraj - 1 year ago 52
Java Question

Convert array of strings into a string in Java

I want the Java code for converting an array of strings into an string.

Answer Source

Either use



StringBuilder builder = new StringBuilder();
for(String s : arr) {
return builder.toString();

You can modify the above depending on what characters, if any, you want in between strings.

You may also see near identical code to the above but using StringBuffer - StringBuilder is a newer class that's not thread-safe, but therefore has better performance in a single thread because it does away with unneeded synchronization. In short, you're better using StringBuilder in 99% of cases - functionality wise, the two are identical.

DON'T use a string and just append to it with += like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.