How to convert a char array back to a string?
To convert a char
array back to a String
in Java, you can use the String
class's constructor that takes a char
array as an argument.
Here's an example of how you can convert a char
array to a String
:
public class Main {
public static void main(String[] args) {
char[] charArray = {'h', 'e', 'l', 'l', 'o'};
String str = new String(charArray);
System.out.println(str); // prints "hello"
}
}
In this example, the char
array is passed to the String
constructor, which creates a new String
object with the same characters as the char
array.
You can also use the String.valueOf()
method to convert a char
array to a String
. For example:
public class Main {
public static void main(String[] args) {
char[] charArray = {'h', 'e', 'l', 'l', 'o'};
String str = String.valueOf(charArray);
System.out.println(str); // prints "hello"
}
}
I hope this helps! Let me know if you have any questions.