Java char to string

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.


 
Ads

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

Share on Google+Share on Google+

Java char to string

Posted on: May 4, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Java char to string  

Post your Comment


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

Ads

 

Ads