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

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

To convert a char array to a string will be using following methods,

  • creating string object by passing char array name ‘charArray’ to the 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.

// java convert char array to string
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