Java Program to convert a string to character

Here we are explaining how to write a java program to convert a string to a character. It's a simple program. First, we have to declare a string variable and convert it into character by using the charAt() method.

How to convert a string to the character in java?

In java, we can convert a string to a character by using charAt() method. An example is shown below:


String str="Good Morning";
char ch=str.charAt(0);//returns G
 

here str is the string that is converted into character. The ch contains the first character of the string str. That is G.

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

First, we have to declare the class StringToChar with the public modifier. Then open the main() function. Then declare the variable str as a string. Assign str as 'Welcome'.By using a for loop with the condition i < str.length and convert each letters of the string into character using ch= str.charAt(i).Then display the converted character.

ALGORITHM

STEP 1: Declare the class StringToChar with the public modifier.

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

STEP 3: Declare the variable str as a string.

STEP 4: Assign str to 'welcome'.

STEP 5: By using a for loop with the condition i < str.length().

STEP 6: convert the string to character by ,char ch=str.charAt(i).

STEP 7: Display the converted character as ch and repeat step 5.

 

Java Source Code

                                          public class StringToChar {
    public static void main(String args[]) {
        String str = "welcome";
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            System.out.println("character at  position " + i + " is: " + ch);
        }
    }
}
                                      

OUTPUT

character at  position 0 is: w
character at  position 1 is: e
character at  position 2 is: l
character at  position 3 is: c
character at  position 4 is: o
character at  position 5 is: m
character at  position 6 is: e