Java Program to convert character to string


April 22, 2022, Learn eTutorial
1036

Here we are explaining how to write a java program to convert a character to a string. So first we have to declare a character variable and assign a value to it. Then convert the character into the string by character.tostring() method and string.valueOf() method. The two methods are explained below

How to convert a character to a string?

we can convert a character to a string in java by two methods.

  1. By using tostring() Method

    Example: String str = Character.toString(ch);

    here ch is the character that is to be converted into a string.

  2. By using valuerOf() method.

    Example: String str2 = String.valueOf(ch);

How to implement the java program to convert character to string?

It is very easy to convert a character to a string in java. First, we have to declare a character variable ch and assign a value to it. Then we can convert the character ch to string by using character.tostring(ch) method. Then we will display the string. Then we also convert the character to a string by using the string.valueOf(ch) method. Then we will display the string using system.out.println().

ALGORITHM

STEP 1: Declare the class CS with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: declare the variable ch as a character and assign the value ch='m'.

STEP 4: Convert the character ch to the string str by using the function character.tostring(ch).

STEP 5: Display the converted string str.

STEP 6: Then Convert the character to string by the second method,str2=String valueOf(ch).

STEP 7: Display the converted string.

Java Source Code

                                          public class CS {
    public static void main(String args[]) {

        char ch = 'm';
        //First Method
        String str = Character.toString(ch);
        System.out.println("Method1:");
        System.out.println("The String is: " + str);

        // Second Method
        String str2 = String.valueOf(ch);
        System.out.println("Method2:");
        System.out.println("The String is: " + str2);
    }
}
                                      

OUTPUT

Method1:
The String is: m
Method2:
The String is: m