How convert an array of Strings in a single String in java?


Using StringBuffer

  • Create an empty String Buffer object.

  • Traverse through the elements of the String array using loop.

  • In the loop, append each element of the array to the StringBuffer object using the append() method.

  • Finally convert the StringBuffer object to string using the toString() method.

Example

public class ArrayOfStrings {
   public static void main(String args[]) {
      String stringArray[] = {"Hello ", " how", " are", " you", " welcome", " to", " Tutorialspoint"};
      StringBuffer sb = new StringBuffer();
      for(int i = 0; i < stringArray.length; i++) {
         sb.append(stringArray[i]);
      }
      String str = sb.toString();
      System.out.println(str);
   }
}

Output

Hello how are you welcome to Tutorialspoint

Using the toString() method of the Arrays class

The toString() method of the Arrays class accepts a String array (in fact any array) and returns it as a String. Pass your String array to this method as a parameter.

Example

import java.util.Arrays;
public class ArrayOfStrings {
   public static void main(String args[]) {
      String stringArray[] = {"Hello ", " how", " are", " you", " welcome", " to", " Tutorialspoint"};
      StringBuffer sb = new StringBuffer();
      for(int i = 0; i < stringArray.length; i++) {
         sb.append(stringArray[i]);
      }
      String str = Arrays.toString(stringArray);
      System.out.println(str);
   }
}

Output

Hello how are you welcome to Tutorialspoint

Using the StringJoiner class

Since Java8 StringJoiner class is introduced this you can construct a sequence of characters separated by desired delimiter.

The add() method accepts a CharacterSequence object (Segment, String, StringBuffer, StringBuilder) and adds it to the current Joiner separating the next and previous elements (if any) with delimiter at the time of constructing it.

The toString() method returns the contents of the current StringJoiner as a Sting object.

Therefore, to convert String array to a single Sting using this class −

  • Create an object of StringJoiner.

  • Traverse through the Sting array using a loop.

  • In the loop add each element of the Sting array to the StringJoiner object.

  • Convert the it to String using the toString() method.

Example

import java.util.StringJoiner;
public class ArrayOfStrings {
   public static void main(String args[]) {
      String stringArray[] = {"Hello", " how", " are", " you", " welcome", " to", " Tutorialspoint"};
      StringJoiner joiner = new StringJoiner("");
      for(int i = 0; i < stringArray.length; i++) {
         joiner.add(stringArray[i]);
      }
      String str = joiner.toString();
      System.out.println(str);
   }
}

Output

Hello how are you welcome to Tutorialspoint

Updated on: 14-Sep-2023

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements