Following program will show you how to convert a char into a string in Java. Though there are many ways to convert a char to a string we will use toString() method. This reads a character and returns the String equivalent of it. In this example a class 'CharToString' is used. System.in is used to read the input from system/user at the run time.
Following program will show you how to convert a char into a string in Java. Though there are many ways to convert a char to a string we will use toString() method. This reads a character and returns the String equivalent of it.
The index of first character is always "0".
In this example a class "CharToString" is used. System.in is used to read the input from system/user at the run time. Scanner class is used to read the input from System.in. (We can also use BufferReader to read the input) Scanner splits the input into substrings consisting of any white space.
Example of converting Java char to string:
package Roseindia; import java.io.IOException; import java.util.Scanner; public class CharToString { public static void main(String args[]) throws IOException { Scanner scanner = new Scanner(System.in); System.out.println("Enter a Character: "); String string = scanner.nextLine(); char ct = string.charAt(0); System.out.println("Character value is " + ct); String s1 = Character.toString(ct); System.out.println("String value is " + s1); } }
OUTPUT:
Enter a Character:
H
Character value is H
String value is H