Converting char to string java: In the previous article we have discussed Java Program to Convert char to int
In this article we will see how to convert a character type to string type.
Program to Convert char to String
How to convert a char to a string in java: Before starting let’s see some examples of String type and char type.
Example-1: String type String a = "BtechGeeks"; String b= "B";
Example-2: char type String a = 88; String b= 'B';
Let’ see different ways to convert a char to string.
Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.
Method 1 : Java Program to Convert char to String Using String.valueOf() method
Convert character to string java: Character can be converted to string by using String.valueOf() method. Lets see how it works.
String.valueOf() is a static overloading method of String class that is used to convert arguments of primitive data types like char, float, etc. to String data type.
Approach :
- Take a character value and store it in a
charvariableinput1 - Then pass that
input1variable as parameter toString.valueOf()method which will convert thechartostringvalue and return it . - Store that string value in a String variable
output. - Display the result.
Program :
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// creating scanner object
Scanner sc = new Scanner(System.in);
// input a character through scanner class
System.out.println("Enter a Character : ");
char input1=sc.next().charAt(0);
// converting to string
String output = String.valueOf(input1);
System.out.println("Converted String is : "+output);
}
}
Output : Enter a Character : e Converted String is :e
Method 2 : Java Program to Convert char to String Using Character.toString() method
Character can be converted to string by using Character.toString() method. Lets see how it works.
toString() is a static method of the Character class which returns a value of data type int represented by a specified Unicode character.
Approach :
- Take a char value and store it in a
charvariableinput1. - Then pass that
input1variable as parameter totoString()method which will convert the char to string value and return it . - Store that string value in a variable
output. - Display the result .
Program :
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// creating scanner object
Scanner sc = new Scanner(System.in);
// input a character through scanner class
System.out.println("Enter a Character : ");
char input1=sc.next().charAt(0);
// converting to string
String output = Character.toString(input1);
System.out.println("Converted String is : "+output);
}
}
Output : Enter a Character : e Converted String is : e
Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.
Related Java Program: