- Given char value in java.
- We would like to convert char to string using following methods.
- toString method of Character class
- valueOf method of String class
- format method of String class
- + operator
Example: char to string in java
Example : Given char = 'M'
Output of program would be "M"
Java methods of String & Character class in Java
Class Name |
Method Name |
Description |
Character |
String toString(char c) |
Returns a String object representing the specified char. |
String |
String valueOf(char c) |
Returns the string representation of the char argument. |
String |
String format(String format, Object… args) |
Returns a formatted string using the specified format string and arguments. |
Program: Convert char to String in java
package org.learn.beginner;
public class ConvertCharToString {
public static void main(String[] args) {
char chInput = 'M';
System.out.println("Input Character : "+ chInput);
//Convert char to string using Character.toString
String strValue = Character.toString(chInput);
System.out.println("String using Character.toString: " +strValue);
//Convert char to string using String.valueOf
strValue = String.valueOf(chInput);
System.out.println("String using String.valueOf: " +strValue);
//Convert char to string using String.format
strValue = String.format("%c", chInput);
System.out.println("String using String.format: " +strValue);
//Convert char to string using + operator
strValue = ""+chInput;
System.out.println("String using + operator: " +strValue);
}
}
Output: char to string using String, Character & + operator
Input Character : M
String using Character.toString: M
String using String.valueOf: M
String using String.format: M
String using + operator: M