In Java, it is possible to convert between characters and strings using various built-in methods.
In this tutorial, we will discuss how to convert a character to a string and vice versa.
Converting Character to String
To convert a character to a string, we can use the built-in method Character.toString().
Here’s an example:
char c = 'a'; String s = Character.toString(c);
In the above example, we declare a character c with the value ‘a’.
We then use the Character.toString() method to convert c to a string and assign the result to the variable s.
Another way to convert a character to a string is to concatenate it with an empty string.
Here’s an example:
char c = 'a'; String s = "" + c;
In the above example, we concatenate an empty string with the character c to convert it to a string.
Converting String to Character
To convert a string to a character, we can use the charAt() method.
Here’s an example:
String s = "hello"; char c = s.charAt(0);
In the above example, we declare a string s with the value “hello”.
We then use the charAt() method to get the character at the specified index (0 in this case) and assign the result to the variable c.
It’s important to note that if the string contains more than one character, only the first character will be returned by the charAt() method.
If you want to convert a string containing multiple characters to an array of characters, you can use the toCharArray() method.
Here’s an example:
String s = "hello"; char[] chars = s.toCharArray();
In the above example, we declare a string s with the value “hello”.
We then use the toCharArray() method to convert s to an array of characters and assign the result to the variable chars.
Conclusion
In Java, converting between characters and strings is a common task.
By using the built-in methods discussed in this tutorial, you can easily convert characters to strings and vice versa in your Java programs.




