Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-conversion Java char to string

Related Tutorials


 
 

Share on Google+Share on Google+

Java char to string

Advertisement
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.

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:

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 7, 2013

Related Tutorials

Discuss: Java char to string  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com