Java Program to Convert Character to String

Write a Java program to convert character to string with an example. In this programming language, there is a toString function that converts the character into a string.

Java Program to Convert Character to String using toString

In this 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  = " + str1);
		System.out.println(str1.getClass().getName());
		
		String str2 = Character.toString(ch2);
		System.out.println("Output  = " + str2);
		System.out.println(str2.getClass().getName());

	}
}
Output = a
java.lang.String
Output = m
java.lang.String

Apart from toString, there is a Java valueOf function to convert character to string. In this example, we use this 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 = " + str1);
		System.out.println(str1.getClass().getName());
		
		String str2 = String.valueOf(ch2);
		System.out.println("valueOf Output = " + str2);
		System.out.println(str2.getClass().getName());

	}
}
valueOf Output = g
java.lang.String
valueOf Output = t
java.lang.String

This program allows entering any character and converting 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

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.