Convert char array to string in java

Let’s learn convert char array to string in java.

Convert char array to string in java

char array to string in java or character array to string in java is the most asked java interview question.

convert char array to string in java

To convert a char array to a string there are two ways.

Using Constructor: creating string object and passing char array name ‘charArray’ to the string constructor. Here’s the java program.

// java convert array of char to string
public class CharArrayToString
{
   public static void main(String[] args)
   {
      char[] charArray = new char[]{'F','l','o','w','e','r','B','r','a','c','k','e','t','s'};
      String str = new String(charArray);
      System.out.println(str);
   }
}


Output:

FlowerBrackets


Using valueof() method: valueOf() method of String class returns string that contains the characters of the character array.

public class CharArrayToStringUsingValueOf
{
   public static void main(String[] args)
   {
      char[] charArray = new char[]{'F','l','o','w','e','r','B','r','a','c','k','e','t','s'};
      String str = String.valueOf(charArray);
      System.out.println(str);
   }
}


Output:

FlowerBrackets


Using StringBuilder: Here we iterate over characters and append each character to StringBuilder.

Finally we are calling toString() method on StringBuilder class.

toString() method returns string representation of given sequence of characters.

public class CharArrayToStringUsingStringBuilder
{
   public static void main(String[] args)
   {
      char[] chArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
      StringBuilder sb = new StringBuilder();
      for(char ch: chArray)
      {
         sb.append(ch);
      }
      String str = sb.toString();
      System.out.println(str);
   }
}


Output:

Hello World