Java – How to convert Char to String

A Java example to show you how to convert a Char into a String and vise verse.

ConvertCharToString.java

package com.mkyong.utils;

public class ConvertCharToString {

    public static void main(String[] args) {

        String website = "https://mkyong.com";

        //convert a String into char
        char charH = website.charAt(0); //h
        char charP = website.charAt(3);//p
        char charM = website.charAt(11);//m
        System.out.println(charH);
        System.out.println(charP);
        System.out.println(charM);

        //convert char back to String
        String temp = Character.toString(charM);

        if ("m".equals(temp)) {
            System.out.println("match");
        }

    }

}

Output

h
p
m
match

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Diva
10 years ago

you can find some more details in the below link,”http://javadomain.in/char-to-string-in-java/”

Kevin
10 years ago

You sir, are God sent. The small amount of code you have shown here has been more enlightening than the majority of forums I have searched.

I am now able to figure out how to get the basic concept for ‘reversing text in a file’.

This is what I have so far, it is definitely not complete and does not reverse all the text in a file. However, with the basic concept you have displayed using the toString() method in the Character class, I have the following code in my test driver:

public class ReverseText
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File(“Solar_System_Info.txt”);

Scanner in = new Scanner(inputFile);

String info = in.nextLine();

char processInfo = info.charAt(info.length()-1);

String reverse = Character.toString(processInfo);

char processInfo2 = info.charAt(info.length()-2);

reverse = reverse + Character.toString(processInfo2);

System.out.println(reverse);

}

Max Dalton
11 years ago

Thanks for this, very nice explanation.

Jamie
12 years ago

this example seems more to be for converting strings to char and why are throwing in the if statment? just confuses the issue