Today we will look into java char to String program. We will also learn how to convert String to a char array.
Before we look into java char to String program, let’s get to the basic difference between them.
We can use String.valueOf(char c)
or Character.toString(char c)
to convert char to string. Below is the example program showing how to use these methods to convert char to string.
public class JavaCharToString {
public static void main(String[] args) {
char c = 'X';
String str = String.valueOf(c);
String str1 = Character.toString(c);
System.out.println(c + " char converted to String using String.valueOf(char c) = " + str);
System.out.println(c + " char converted to String using Character.toString(char c) = " + str1);
}
}
java.lang.Character
is the wrapper class for primitive char data type. Character.toString(char c)
internally calls String.valueOf(char c)
method, so it’s better to use String class function to convert char to String. Output of the above program is shown in below image.
Since String is an array of char, we can convert a string to the char array. String class also has a method to get the char at a specific index. Let’s look at a simple program to convert String to a char array.
import java.util.Arrays;
public class JavaStringToCharArray {
public static void main(String[] args) {
String str = "journaldev.com";
// get char at specific index
char c = str.charAt(0);
// Character array from String
char[] charArray = str.toCharArray();
System.out.println(str + " String index 0 character = " + c);
System.out.println(str + " String converted to character array = " + Arrays.toString(charArray));
}
}
To get the char from a String object, we can use chatAt(int index)
method. Whereas toCharArray()
returns the char array of the String. Here we are using Arrays.toString(char[] ca)
method to print the char array in readable format. Output of the above program is shown below. That’s all for the char to String and String to char array conversion. Reference: Character API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.