English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to convert a character (char) to a string and vice versa in Java.
public class CharString { public static void main(String[] args) { char ch = 'c'; String st = Character.toString(ch); // or // st = String.valueOf(ch); System.out.println("The string is: ") + st); } }
When the program is run, the output is:
The string is: c
In the above program, we stored a character in the variable ch. We use the Character class's toString() method to convert the character to a string st.
Additionally, we can also use the String's valueOf() method for the conversion. However, both are the same internally.
If you have a char array instead of just a char, we can easily convert it to a string using the String method, as shown below:
public class CharString { public static void main(String[] args) { char[] ch = {'a', 'e', 'i', 'o', 'u'}; String st = String.valueOf(ch); String st2 = new String(ch); System.out.println(st); System.out.println(st2); } }
When the program is run, the output is:
aeiou aeiou
In the above program, we have a char array ch containing vowels. We use the String's valueOf() method again to convert the character array to a String.
We can also use the String constructor with the character array ch as the conversion parameter.
We can also use the String's toCharArray() method to convert a string to a char array (but not to a char).
import java.util.Arrays; public class StringChar { public static void main(String[] args) { String st = "This is great"; char[] chars = st.toCharArray(); System.out.println(Arrays.toString(chars)); } }
When the program is run, the output is:
[T, h, i, s, , i, s, , g, r, e, a, t]
In the above program, we store a string in the variable st. We use the String.toCharArray() method to convert the string to a character array stored in chars.
Then, we use the Arrays.toString() method to print the elements in the form of a chars array.