Java allows users to convert a character array, char[] arr
, to a String
.
There are numerous ways to do so. Let’s look at each of them in detail:
String
constructorThe simplest conversion method is passing the character array to a String constructor.
By default, the String
constructor uses a copyOf()
method to copy the character array into the String
.
Consider the following example:
class HelloWorld {public static void main( String args[] ) {char[] array = {'H','e','l','l','o'};String string = new String(array);System.out.printf("Resultant String is: %s" , string);}}
StringBuilder
The StringBuilder
class in Java is used to create mutable, i.e., modifiable String
objects.
Follow the steps to successfully convert a character array to a String
using the StringBuilder
class:
StringBuilder
objectStringBuilder
object using the built-in append()
methodStringBuilder
object to a String
using the toString()
methodLook at the following code to see how this works:
class HelloWorld {public static void main( String args[] ) {char[] array = {'H','e','l','l','o'};StringBuilder setbuilder = new StringBuilder();for (int i=0; i < array.length; i++){setbuilder.append(array[i]);}String string = setbuilder.toString();System.out.printf("Resultant String is: %s" , string);}}
copyValueOf( )
or valueOf( )
methodsThe copyValueOf()
and valueOf()
methods in Java essentially do the same thing, i.e., return a String
based on a particular character array.
The following codes demonstrate their use:
class HelloWorld {public static void main( String args[] ) {char[] array = {'H','e','l','l','o'};String string = String.copyValueOf(array);System.out.printf("Resultant String is: %s" , string);}}
Free Resources