How to convert a char array to a string in Java?

There are two ways to convert a char array (char[]) to String in Java:
1) Creating String object by passing array name to the constructor
2) Using valueOf() method of String class.

This example demonstrates both the above mentioned ways of converting a char array to String. Here we have a char array ch and we have created two strings str and str1 using the char array.

class CharArrayToString
   public static void main(String args[])
      // Method 1: Using String object
      char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
      String str = new String(ch);
      // Method 2: Using valueOf method
      String str2 = String.valueOf(ch);

good morning
good morning

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.