Google News
logo
How to convert a char array to a string in Java?
To convert a char array to a string in Java, you can use the String class constructor that takes a char[] as its argument. Here's an example :
Program :
class CharArrayToString
{
   public static void main(String args[])
   {
      // Method 1: Using String object
      char[] ch = {'H', 'e', 'l', 'l', 'o'};
      String str = new String(ch);
      System.out.println(str);
 
      // Method 2: Using valueOf method
      String str2 = String.valueOf(ch);
      System.out.println(str2);
   }
}
Output :
Hello
Hello
In this example, we first declare and initialize a char[] array called charArray with the characters 'H', 'e', 'l', 'l', 'o'. We then create a new String object called str by passing charArray to the String constructor. Finally, we print str to the console using System.out.println().