Convert char array to string in java

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

convert char array to string in java

Convert char array to string in java

In java we will be creating string object by passing char array name to the constructor. Here’s the java program,

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 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 string = sb.toString();
      System.out.println(string);
   }
}



Output:

Hello World