Convert char array to string in java

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

Convert char array to string in java

How to convert 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 will be using following methods,

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 CharArrayToStringDemo
{
   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.

Also read – interface in java

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

public class CharArrayToString
{
   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