Java Program to convert character array to string


March 22, 2022, Learn eTutorial
922

Here we are explaining how to write a java program to convert character array to string. It's a simple program and easy to understand.

How to convert character array into string in java?

We can convert a character array into a string by two methods.

1) By Using String.valueOf() method.

2) By using a string object.

How to implement the java program to convert a character array into a string?

First, we have to declare the class ChToS.Then open the main function. Declare a character array ch and assign a value for it. Then first convert the character array into a string by using the String.valueOf() method and display it. Then by using the string object method converts the character array into a string, and displays it.

ALGORITHM

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

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

STEP 3: Create the character array ch and assign some values.

STEP 4: By using the first method, convert the character array into ch as String S1=String.valueOf(ch).

STEP 5: Then display S1.

STEP 6: By using the second method, create a string variable S2 bypassing the character array ch as the parameter.

STEP 7: Then display S2.

 

Java Source Code

                                          public class ChToS {
    public static void main(String args[]) {
        char[] ch = {
            'h',
            'o',
            'w',
            ' ',
            'a',
            'r',
            'e',
            ' ',
            'y',
            'o',
            'u',
            '?'
        };
        //First Method:Value Of
        String S1 = String.valueOf(ch);
        System.out.println(S1);

        // Second Method

        String S2 = new String(ch);
        System.out.println(S2);


    }
}
                                      

OUTPUT

how are you?
how are you?