How to convert a character array to the string in Java?

Hello Everyone! In this tutorial, we will learn how to convert a character array to the string in java programming language.

There are different ways to do that-
1.By creating a string object by passing the required array name to the constructor.
2.By using copyValueOf() or valueOf()  which are the built-in methods of String class in java.

let’s understand the above ways one by one with the help of the following example –

Java program to convert a character array to the string

1. In this technique, we just simply pass the name of the character array as an argument to String constructor.

class Main
{
   public static void main(String args[])
   {
      char[] charray = {'c', 'o', 'd', 'e', 's', 'p', 'e', 'e', 'd', 'y'};
      // By passing array name to String constructor
      String s1 = new String(charray);
      System.out.println(s1);
   }
}

the output of the above code is:

codespeedy

2. In this technique, we will call copyValueOf() or valueOf() methods which are the built-in method of String class and we will the pass the name of character array as an argument to these methods.

class Main 
{ public static void main(String args[])
    { 
          char[] charray = {'c', 'o', 'd', 'e', 's', 'p', 'e', 'e', 'd', 'y'}; 
          // By calling valueOf() method 
          String s1 = String.valueOf(charray);
          System.out.println(s1); 
          // By calling copyValueOf() method
          String s2= String.copyValueOf(charray);
          System.out.println(s2);
    } 
}

the output of the above code is:

codespeedy
codespeedy

Cheers! now you understood how to convert a character array to the string.

you may also read :

String palindrome in java

Compare two strings in java

Leave a Reply

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