It is sometimes desirable to convert a character to a string. We do this using the toString() method contained in the Character class:
String s = instanceOfClassCharacter.Character.toString();
To create an instance of the class character we use the Character constructor:
Charcater(char c);
Some sample code is presented in Table 1 that implements the above together with some appropriate output in Table 2.
// CHARACTER 2 STRING APPLICATION
// Frans Coenen
// Thursday 6 April 2000
// The University of Liverpool, UK
import java.io.*;
class Char2String {
// ------------------- FIELDS ------------------------
// Create BufferedReader class instance
static BufferedReader keyboardInput = new
BufferedReader(new InputStreamReader(System.in));
// ------------------ METHODS ------------------------
public static void main(String[] args) throws IOException {
// Input a character and output as a string
System.out.print("Input a character: ");
char myChar = (char) keyboardInput.read();
// Output the result
System.out.println("Character is: '" + myChar + "'");
// Output the result as a string
String myString = new Character(myChar).toString();
System.out.println("String is: \"" + myChar + "\"");
}
}
|
Table 1: Character to string conversion
$ java Char2String Input a character: g Character is: 'g' String is: "g" |
Table 2: Sample output
Created and maintained by Frans Coenen. Last updated 02 October 2003