Convert char array to String
How to convert char array to String in Java
In this post, we are going to convert the char array to String in Java. The char array is a collection of characters and an object while String is a sequence of characters and a class in Java.
The string is the most common and mostly used datatype for data handing in Java. So, if we have a char array and need to get it into String then we need to convert the char array to string.
To convert a char array to a string, we are using String class constructor, valueOf(), and copyValueOf() method of String class.
The string class provides a constructor for the char array argument to create a string. We are using it to get String from the char array.
The valueOf() method of String class accept char array argument and return a String as a result. similarly, copyValueOf() method can be used to get a string from char array. both the methods are equal, we can use any of them.
Time for an Example:
Let's create an example to get a string from a char array. Here, we are using a string's constructor that returns a string from a char array.
public class Main {
public static void main(String[] args){
char[] ch = {'a','e','i','o','u'};
System.out.println(ch);
// convert char to string
String str = new String(ch);
System.out.println(str);
System.out.println(str.getClass().getName());
}
}aeiou aeiou java.lang.String
Example: Convert by using the valueOf() method
Let's create another example to get a string from a char array. Here, we are using the valueOf() method that converts a char array to a string object.
public class Main {
public static void main(String[] args){
char[] ch = {'a','e','i','o','u'};
System.out.println(ch);
// convert char to string
String str = String.valueOf(ch);
System.out.println(str);
System.out.println(str.getClass().getName());
}
}aeiou aeiou java.lang.String
Example: Convert by using the copyValueOf() method
Here, we are using copyValueOf() method to get a string from a char array. It is equivalent to the valueOf() method has no significant difference.
public class Main {
public static void main(String[] args){
char[] ch = {'a','e','i','o','u'};
System.out.println(ch);
// convert char to string
String str = String.copyValueOf(ch);
System.out.println(str);
System.out.println(str.getClass().getName());
}
}aeiou aeiou java.lang.String










