java

How to convert a char array to a string in Java

In this tutorial, we are going to see different ways to convert a char array to a string in Java.

  • Using the String constructor
  • Using the valueOf method

 

Method 1: Using the String constructor

Here we have a char array ‘arr’ and we have created a string ‘str’ using the String constructor (new String()).

public class Main
{
  public static void main(String args[])
  {
     char[] arr = {'H','i',' ','S','t','a','c','k','H','o','w','T','o'};
     String str = new String(arr);
     System.out.println(str);
  }
}

Output:

Hi StackHowTo

 

 

Method 2: Using the valueOf method

Here we have a char array ‘arr’ and we have created a string str’ using the valueOf method.

public class Main
{
  public static void main(String args[])
  {
     char[] arr = {'H','i',' ','S','t','a','c','k','H','o','w','T','o'};
     String str = String.valueOf(arr);
     System.out.println(str);
  }
}

Output:

Hi StackHowTo
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *