Converting a character array to a string in Java

Share

Java allows users to convert a character array, char[] arr, to a String.

svg viewer

There are numerous ways to do so. Let’s look at each of them in detail:

1. Using the String constructor

The 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);
}
}

2. Using 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:

  1. Create a StringBuilder object
  2. Loop through the character array and append each character to the StringBuilder object using the built-in append() method
  3. Convert the StringBuilder object to a String using the toString() method

Look 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);
}
}

3. Using copyValueOf( ) or valueOf( ) methods

The 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);
}
}
Copyright ©2024 Educative, Inc. All rights reserved