Organizational Research By

Surprising Reserch Topic

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.

Example:
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);
      System.out.println(str);
 
      // Method 2: Using valueOf method
      String str2 = String.valueOf(ch);
      System.out.println(str2);
   }
}
Output:

good morning
good morning
asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
43 views



Related Hot Questions



Government Jobs Opening


...