Explain Codes LogoExplain Codes Logo

Convert array of strings into a string in Java

java
string-concatenation
stringbuilder
textutils
Anton ShumikhinbyAnton Shumikhin·Jan 26, 2025
TLDR

Transform a string array into a single string with String.join():

String[] words = {"Java", "is", "wonderful"}; String singleStr = String.join(" ", words); // "Java is wonderful"

Or, harness the power of Java 8 streams for an identical outcome:

String singleStr = Arrays.stream(words).collect(Collectors.joining(" "));

These methods couple array elements with a space, creating a cohesive, legible string.

Concrete join methods

StringBuilder: For custom scenarios

Need a mutable sequence of characters or have unusual requirements? StringBuilder is your buddy:

String[] words = {"Java", "is", "mighty"}; StringBuilder sb = new StringBuilder(); for (String word : words) { sb.append(word).append(" "); // Adding SpaceStation after each word } sb.setLength(sb.length() - 1); // Shhh...Last trailing space didn't pay rent! String result = sb.toString();

When in Android land, use TextUtils.join()

For Android developers, TextUtils.join() acts as a lifesaver:

String[] words = {"Android", "coding", "is", "fun"}; String result = TextUtils.join(" ", words);

Third-party libraries: There's an Apache for that

Got Apache Commons Lang or Guava's Joiner handy? They've got you covered:

// Wind of Apache blowing your way String[] words = {"Java", "enhances", "creativity"}; String result = StringUtils.join(words, " "); // Going nuts with Guava's Joiner String[] words = {"Practically", "Java", "rocks"}; String result = Joiner.on(" ").skipNulls().join(words);

Considerations and trapdoors

This sign says "No += allowed in loops"

Incrementing += for concatenation in a loop? Not so fast! It ends up creating excess string objects:

String res = ""; for(String word : words) { res += word + " "; // Don't do that. It's traumatizing for Java! }

Big arrays? Beware of memory footprint

Handling gargantuan arrays? Keep an eye on memory usage:

// Pray to the JVM gods for memory! String[] bigArray = createAMassiveArrayOfStrings(); String result = String.join(" ", bigArray);

Going the extra mile

Null handling with finesse

Have an array that might contain null? Choose the right method:

String[] words = {"Java", null, "is", null, "versatile"}; String result = Arrays.stream(words) .filter(Objects::nonNull) .collect(Collectors.joining(" "));

Multithreading needs StringBuffer

Calling StringBuffer to the rescue in multithreaded scenarios:

StringBuffer sb = new StringBuffer(); // Thread-safe operations happening here! String result = sb.toString();

No explicit arrays needed with pipeline

Forge a path directly within a stream pipeline:

String result = Stream.of("Pro", "Java", "Tips") .collect(Collectors.joining(", "));