Convert Character to String and Vice-Versa in Java

Exercise:

Write a Java Program to convert character to string and vice-versa.

1.Convert char to String

Click Here to View the Solution!
public class CharString {
 
    public static void main(String[] args) {
        char ch = 'e';
        String st = Character.toString(ch);
        
        // st = String.valueOf(ch);
        System.out.println("The string is: " + st);
    }
} 
Click Here to View the Output!
The string is: e
Click Here to View the Explanation!
  • This program is used to convert a character to a string by using a .toString method in Java.
  • Initially, a character ‘e’ is stored in a character variable ch.
  • Java’s Character class provides a method .toString that is used in this program to change a character to a string ‘st’ as follows: Charcter.toString(ch).
  • Finally, the converted character is printed as a string which is stored in a string variable st.

2.Convert char array to String

Click Here to View the Solution!
public class CharString {
         public static void main(String[] args) {
         char[] ch = {'H', 'e', 'l', 'l', 'o'};
  
         String st = String.valueOf(ch);
         System.out.println(st);
     }
 } 
Click Here to View the Output!
Hello
Click Here to View the Explanation!
  • This program is used to convert a character array into a string by using a method valueof() of String.
  • Initially, a character array ch is initialized containing the following characters h,e,l,l,o.
  • The String method valueof() is stored in a string variable st. which is given ch as the parameter. This will convert the characters into a string.
  • Similarly, a String constructor can also be used for the same purpose. Which is initialized as st2.
  • Finally, both st and st2 are printed. And the output will be hello.

3.Convert String to char array

Click Here to View the Solution!
import java.util.Arrays;
public class StringChar {
   public static void main(String[] args) {
        String st = "This is best  website";
        char[] chars = st.toCharArray();
        System.out.println(Arrays.toString(chars));
    }
} 
Click Here to View the Output!
[T, h, i, s,  , i, s,  , b, e, s, t,    , w, e, b, s, i, t, e]
Click Here to View the Explanation!
  • This program is used to convert a given string into a character array by using a method of String toCharArray().
  • Initially, a string variable is initialized as st that holds the string “This is best website”.
  • The toCharArray() method is initialized for st in a new character array chars. The reason behind initializing an array and not a character is that toCharArray() converts a string to a character array and not into a character.
  • Lastly, the toString() method of the Array class in Java is used to print all the characters of the string st in the form of an array as follows: [T, h, i, s,  , i, s,  , b, e, s, t,  , w, e, b, s, i, t, e]