Java Program to Convert Character to String

Write a Java program to convert character to string with an example. In Java, there is a toString character function that converts the character into a string. In this Java example, we declared two characters and converted them to string using the toString function. To show you the proof, we used str1.getClass().getName() to print the data type of the output.

public class CharToString {
	public static void main(String[] args) {
		
		char ch1 = 'a';
		char ch2 = 'm';
		
		String str1 = Character.toString(ch1);
		System.out.println("Output of Character to String = " + str1);
		System.out.println(str1.getClass().getName());
		
		String str2 = Character.toString(ch2);
		System.out.println("Output of Character to String = " + str2);
		System.out.println(str2.getClass().getName());

	}
}
Output of Character to String = a
java.lang.String
Output of Character to String = m
java.lang.String

Apart from toString, there is a Java valueOf string function to convert character to string. In this Java example, we use this string valueOf function.

public class CharToString2 {
	public static void main(String[] args) {
		
		char ch1 = 'g';
		char ch2 = 't';
		
		String str1 = String.valueOf(ch1);
		System.out.println("valueOf Output - Character to String = " + str1);
		System.out.println(str1.getClass().getName());
		
		String str2 = String.valueOf(ch2);
		System.out.println("valueOf Output - Character to String = " + str2);
		System.out.println(str2.getClass().getName());

	}
}
valueOf Output - Character to String = g
java.lang.String
valueOf Output - Character to String = t
java.lang.String

This Java program allows entering any character and converts it into a string using toString and valueOf functions.

import java.util.Scanner;

public class CharToString3 {
	private static Scanner sc;
	
	public static void main(String[] args) {
		char ch;
		sc= new Scanner(System.in);

		System.out.print("Please Enter any Character =  ");
		ch = sc.next().charAt(0);
		
		String s1 = String.valueOf(ch);
		String s2 = Character.toString(ch);
		
		System.out.println(s1);
		System.out.println(s1.getClass().getName());
		
		System.out.println(s2);
		System.out.println(s2.getClass().getName());
		
	}
}
Java Program to Convert Character to String 1