Learn how to Convert Char to String in Java using four different methods with programming examples for each method:
In this tutorial, we will cover the various ways of converting Java primitive data type char values to data type String.
We will be learning the following methods in Java for char to String conversion:
- String.valueOf()
- Character.toString(char c )
- Character class toString()
- String concatenation
=> Take A Look At The Java Beginners Guide Here
What You Will Learn:
Convert Char To String In Java
Java char is a primitive data type, char data type variable holds only a single character. For Example, alphabets like ‘a’, ‘A’, or numbers like ‘1’, ‘2’ etc., and also special characters like ‘@’, ‘!’ etc.
In some scenarios, this data needs to be converted to Java String class type. A String class is not a Java primitive data type.
For example, in the Java program, the input value coming is of primitive data type ‘char’. But this value is needed for further processing or decision-making using String methods. In such cases, char is first converted to String data type as a pre-requisite.
Let’s have a look at the different ways of converting Java primitive data type of char to String data type. We will see each method in detail.
#1) Using String Class valueOf() Method
Let’s have a look at the method signature of the String class’ valueOf () method. This 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.
public static String valueOf(char ch)
This static method of String class receives an argument of primitive data type char and returns the string representation of char argument.
Parameters:
ch: This is a char data type value.
Returns:
The is char argument’s string representation.
Let’s understand how to use the valueOf() method to convert char to String with the help of the following sample program.
In this program, we are performing the following tasks:
- Value of variable customerGender data type char is converted to String type using the String.valueOf() method and,
- The String value of variable gender is used in an if-then statement further to print the appropriate message for the gender on the console.
Here is the sample program:
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to String Java program * using String.valueOf() method * * @author * */ public class CharStringDemo1 { public static void main(String[] args) { // Assign character 'F' to char variable customerGender char customerGender = 'F'; System.out.println("Welcome to WearToShine - Online shopping store for apparel "); //Pass customerGender as an argument to valueOf() method //to parse it to String value String gender = String.valueOf(customerGender); //print String variable gender value System.out.println("gender --->"+gender); //Evaluate equals condition using String gender value //in if-else condition to print appropriate //message on the console if (gender.equalsIgnoreCase("M")) { System.out.println("Welcome Sir, click on 'Men's apparel' link to check " + "our trendy collection of new arrivals : Shirts, Graphic Tees and More "); }else if(gender.equalsIgnoreCase("F")){ System.out.println("Welcome Madam, click on 'Women's apparel' link to check " + "our trendy collection of new arrivals : Skirts, Tops , partywears and More "); }else { System.out.println("Welcome , please help us with your " + "gender to suggest suitable apparel section for you"); } } }
Here is the program Output:
Welcome to WearToShine – Online shopping store for apparel
gender —>F
Welcome Madam, click on ‘Women’s apparel’ link to check our trendy collection of new arrivals : Skirts, Tops , partywears and More
In the above program, we can see the following char variable value:
char customerGender = 'F';
Convert char to String using String.valueOf() method as shown below:
String gender = String.valueOf(customerGender);
This value of gender variable is used in the if-else condition and prints an appropriate message on the console for gender “F” i.e. female as follows:
Welcome Madam, click on 'Women's apparel' link to check our trendy collection of new arrivals : Skirts, Tops , partywears and More
#2) Using Character.toString(char ch) Static Method
The Character class has a static method of toString(). This method returns a value of data type int represented by a specified Unicode character.
Here is the method signature of the toString (char ch) method for char data type:
public String toString(char ch)
This static method returns an object of String that represents this character’s value. The result string has length 1 of the specified char.
ch – This is the char that needs to be converted
Returns:
This is a string representation of the object.
Let’s understand the use of this Character.toString(char ch) method to convert the character to the String value.
Let us have a look at the following sample program where we are performing the following task:
- char data type value is assigned to the ‘resultStatus’ variable. This char value is converted to String using Character.toString(char ch) method and,
- The string variable ‘result’ value is used in the equals condition further in an if-else statement and prints an appropriate result message on the console.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to int Java program * using Character.getNumericValue() * * @author * */ public class CharIntDemo2 { public static void main(String[] args) { // Assign character '1' to char variable char1 char gender = '1'; //Send gender as an argument to getNumericValue() method // to parse it to int value int genderCode = Character.getNumericValue(gender); // Expected to print int value 1 System.out.println("genderCode--->"+genderCode); double interestRate = 6.50; double specialInterestRate = 7; switch (genderCode) { case 0 ://genderCode 0 is for Gender Male System.out.println("Welcome ,our bank is offering attractive interest rate on Fixed deposits :"+ interestRate +"%"); break; case 1 ://genderCode 1 is for Gender Female System.out.println(" Welcome, our bank is offering special interest rate on Fixed deposits "+ "for our women customers:"+specialInterestRate+"% ."+"\n"+" Hurry up, this offer is valid for limited period only."); break; default : System.out.println("Please enter valid gender code "); } } } Here is the program Output: genderCode--->1 Welcome, our bank is offering special interest rate on Fixed deposits for our women customers:7.0% . Hurry up, this offer is valid for limited period only.
Here is the program Output:
Congratulations !! You have successfully cleared the exam.
In the above program, we are converting char variable resultStatus value to String value and assigning it to variable result.
char resultStatus = 'P'; String result = Character.toString(resultStatus);
This String value is further used in if (result.equalsIgnoreCase(“P”)) condition and the following statement gets executed:
System.out.println("Congratulations !! You have successfully cleared the exam.");
Thus, we see a message on the console as below:
Congratulations !! You have successfully cleared the exam.
#3) Using Character Class toString() Method
This is an instance method of Character class which also returns a value of data type String represented by a specified Unicode character.
Here is the method signature of the toString () method:
public String toString()
This method returns an object of String that represents this character’s value. The result string has length 1 which is the value of data type char represented by Character object.
Returns:
This is a string representation of the object.
Let’s understand the use of this toString() method to convert a character to a String value.
Let us have a look at the following sample program where the value needs to be converted to upper case. For that char data type value needs to be first converted to a String value.
In this program we are performing the following tasks:
- Create an instance of Character class.
- Convert this Character instance to String using the toString() method.
- Further, this String value is used for further manipulation i.e. converting to upper case using String method toUpperCase().
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to String Java program * using Character.toString() method * * @author * */ public class CharStringDemo3 { public static void main(String[] args) { // Assign character 'a' to char variable sampleChar char char1 = 'a'; //Pass char1 as an argument to Character() Character sampleChar = new Character(char1); //Convert sampleChar to String using toString String sampleString = sampleChar.toString(); //Convert sampleString to upper case using String toUpperCase() method String upperCaseStr = sampleString.toUpperCase(); //print upperCaseStr string System.out.println("String in upper case --->"+upperCaseStr); } }
Here is the program Output:
String in upper case —>A
So, in the above program, we are converting char variable value ‘a’ to Character value.
char char1 = 'a';
We are first creating an instance of the Character class using Character() constructor.
Character sampleChar = new Character(char1);
Now, invoke toString() method on Character instance sampleChar which converts it to String:
String sampleString = sampleChar.toString();
This sampleChar string can be used further in the program for String manipulation method like toUpperCase():
String upperCaseStr = sampleString.toUpperCase();
#4) Using String Concatenation
This is the simplest but less efficient way of converting char data type value to String class value. In this way, the char data type value is concatenated with the String.
Let us understand this with the following sample program.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert char to String Java program * using concatenation method * * @author * */ public class CharStringDemo4 { public static void main(String[] args) { char x = 'A'; String sampleString = ""+x; System.out.println("sampleString --->"+sampleString); } }
Here is the program Output:
sampleString —>A
In the above sample code, we have concatenated char x with String “ “ to convert it to a String value.
char x = 'A'; String sampleString = ""+x;
With this, we have covered all the ways of converting Java char to String. Now, let us have a look at the frequently asked questions.
FAQs
Q #1) Can you add char to string Java?
Answer: In Java, you can append char to String by concatenating char value with String.
For Example,
char a = 'M'; String sampleStringValue = ""+a;
Q #2) Can a char be a string?
Answer: The char can be converted to String class value using the below Java class methods:
- String.valueOf()
- Character.toString(char c )
- Character class toString()
- String concatenation
Q #3) What is the difference between char and string?
Answer: char is Java’s primitive data type. It holds a single character which could be a letter, number, or a special character. char data type variable is assigned a single character value enclosed with a single quote ‘ ’.
For Example,
char x = ‘a’;
Char x = ‘1’;
Char x = ‘@’;
Whereas String is a Java class. String class is used by creating an instance of it or assigning value to it. It holds a multiple numbers of characters. String class variable is assigned a sequence of characters enclosed within double quotes “ ”.
For Example,
String x = “abc”;
String x = “1234”;
String x = “1@3a”;
Conclusion
In this tutorial, we have seen the below ways of converting Java primitive data type char values to Java String class values:
- String.valueOf()
- Character.toString(char c )
- Character class toString()
- String concatenation
We have covered each of these ways in detail and explained the use of each method with the help of a sample Java program.
=> Check ALL Java Tutorials Here