Java program to convert a character to string:
In this post, I will show you how to convert a character to String in Java. Character to String conversion is required many times while you develop any Java applications. For example, if we are receiving the data as a character and we want to pass it to a method as String, we need to first convert this character to a string before calling that method.
We will learn different ways to convert a character to a string in this post.
Method 1: By using String.valueOf:
We can use the String.valueOf method. This method takes one character as the parameter and returns one String, i.e. the character as the string.
The below program uses String.valueOf to convert a character to string:
public class Main {
public static void main(String[] args) {
Character ch = 'a';
String chString = String.valueOf(ch);
System.out.println("Final String : " + chString);
}
}
If you run this, it will print output as like below:
Method 2: By using Character.toString():
Character.toString() is another method defined in the Character class. It takes one character as the parameter and returns its String value.
Below Java program uses Character.toString() to convert a character to string:
public class Main {
public static void main(String[] args) {
Character ch = 'a';
String chString = Character.toString(ch);
System.out.println("Final String : " + chString);
}
}
It will print similar output.
Both of these methods give the same result. You can use any one of them.
You might also like:
- Java program to get the epoch timestamp
- How to convert a negative number to positive in Java
- Java program to find the maximum element in a HashSet
- How to add items to a HashSet in Java
- How to remove specific items or remove all items from a HashSet
- 3 different ways to iterate over a HashSet in Java
- 3 different ways in Java to convert comma-separated strings to an ArrayList