Home Java Javatutorial Java char to string
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java char to string

Advertisement
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

Advertisements

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: May 4, 2013

Ask Questions?    Discuss: Java char to string  

Post your Comment


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