The toString(char c)
method can be used to convert any char
variable to its string representation. Let's test this by allowing the user to input a character and converting it to a string.
public class CharToString {
public static void main(String[] args) {
// Step 1: Declare a Scanner object for user input
Scanner input = new Scanner(System.in);
// Step 2: Prompt the user for input
System.out.println("Enter a character:");
// Step 3: Read the input character
char ch = input.next().charAt(0);
// Step 4: Convert char to String
String str = Character.toString(ch);
// Step 5: Output the results
System.out.println("The character is: " + ch);
System.out.println("The string is: " + str);
}
}
In this code, an instance of the Scanner
class is used to read user input and the charAt(0)
method is used to get the first character of the input string. Now let's compile and run the code. Use the following command:
javac CharToString.java && java CharToString
This will compile and execute the program. You should see the program prompting the user for input and then converting the entered character to its string representation.