Write a java program to convert Character to string and Vice versa
Here we will take three different examples to understand this program.
Example 1: Convert char to String Example 2: Convert char array to String Example 3: Convert String to char array
Example 1: Convert char to String
public class CharToString { public static void main(String[] args) { char ch = 'x'; String st = Character.toString(ch); // you can also use below function // st = String.valueOf(ch); System.out.println("The string is: " + st); } }
Output
The string is: x
Here we are using Character class’s toString()
method to convert a character to string. Alternatively, we can use String.valueOf(ch)
to convert a character to String.
To understand below program, you need to have a little bit understanding about Arrays.
Example 2: Convert char array to String
public class CharArrayToString { public static void main(String[] args) { char[] ch = {'a', 'b', 'c', 'd', 'e'}; String st = String.valueOf(ch); String st2 = new String(ch); System.out.println(st); System.out.println(st2); } }
Output
abcde abcde
In the above program, we have defined the character array in ch variable. here, we are using valueOf(ch)
method of String class to convert array directly to string. Alternatively, we can also define a new String Object and pass the character array into argument. The output will be same.
Example 3: Convert String to char array
import java.util.Arrays; public class StringToChar { public static void main(String[] args) { String st = "Hello World"; char[] chars = st.toCharArray(); System.out.println(Arrays.toString(chars)); } }
Output
[H,e,l,l,o, ,W,o,r,l,d]
In the above program we are converting a String to a character but its not a one word string. So, to hold the String we need to have array of characters and we have defined it as char[]
.