Java char to string

Here we have given two examples of how to convert a char into a string in Java. In one example we have used Scanner class while in other we have used BufferReader.

Java char to string

Here we have given two examples of how to convert a char into a string in Java. In one example we have used Scanner class while in other we have used BufferReader.

Java char to string

There are many ways to convert a char into a string in Java, one of them is using Scanner class. In this section we have also used BufferReader to convert a char to a string.

The index of first character is always "0".

In Scanner class example, we have used toString() method, which reads a character and returns the String equivalent of it. System.in reads the input from system/user at the run time. Scanner class then reads the input from System.in and splits it into substrings consisting of any white space.

Example of converting char to string using Scanner Class:

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:

M

Character value is M

String value is M

In BufferReader example, we have used toString() method, which converts the character into an integer type data and returns string object representing this character's values. System.in reads the input from system/user at the run time. BufferReader then reads the input from System.in and splits it into substrings consisting of any white space.

Example of converting char to string using BufferReader:

import java.io.*;
import java.lang.*;

public class CharToString{
public static void main(String args[])throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a Character:");
String s = read.readLine();
char c = s.charAt(0);
System.out.println("Character value is " + c);
String s1 = Character.toString(c);
System.out.println("String value is " + s1);
}
}

Output:

C:\corejava>java CharToString

Enter a Character:
P
Character value is P
String value is P

C:\corejava>

Resource: