Home »
Java programming language
Convert a character array to the string in Java
Java | Convert character array to string: Here, we are going to learn how to convert a character array to the string in Java?
Submitted by IncludeHelp, on February 15, 2019
Given a character array and we have to convert it to the string in Java.
Java char[] to string conversion
There are two ways to convert a character array to the string in Java, which are,
- Using String.valueOf(char[]) method
- By creating a new string with character array
1) Java char[] to string example: Using String.valueOf(char[]) method
valueOf() method is a String class method, it accepts a character array and returns the string.
Example:
public class Main
{
public static void main(String[] args) {
char[] charArray = {'I', 'n', 'c', 'l', 'u', 'd', 'e', 'h', 'e', 'l', 'p'};
String str ="";
//converting from char[] to string
str = String.valueOf(charArray);
//printing value
System.out.println("str = " + str);
}
}
Output
str = Includehelp
Java char[] to string example: by creating a new string with character array
We can create a new string with the character array.
Syntax:
String str_var = new String(char[]);
Example:
public class Main
{
public static void main(String[] args) {
char[] charArray = {'I', 'n', 'c', 'l', 'u', 'd', 'e', 'h', 'e', 'l', 'p'};
String str ="";
//creating a new string from char[]
str = new String(charArray);
//printing value
System.out.println("str = " + str);
}
}
Output
str = Includehelp
TOP Interview Coding Problems/Challenges