Java Program to Convert Character to String and String to Character

In this java program, we will learn about how to convert a character to a string and to convert a string to a character.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Convert a Character(char) to String

In Java, there are several different ways to convert a Char to a String. Here, we are converting a Character to a String using the toString() method of the Character class. As an alternative, we may transform a character to a String by using String.valueOf() method also.

public class CharToString {
  public static void main(String[] args) {
    char character = 'T';
    String str = Character.toString(character);

    System.out.println("String value is " + str);
  }
}
Output
String value is T

Java Program to Convert a String to Character(char) Array

In this java program we are converting a String to a Character array. An array can contain more than one character. Hence, to store all the characters of a string we need to have array of characters and we have defined it as char[]. To convert the string into an array of characters, we used toCharArray() method of the String class.

public class StringToCharArray {
  public static void main(String[] args) {
    String str = "Hello World";
    int length = str.length();
    // Convert String to char array
    char[] chars = str.toCharArray();

    // Print char array
    for(int i = 0; i < length; i++) {
      //print character at index i
      System.out.println("Index " + i +
              ", Character " + chars[i]);
    }
  }
}
Output
Index 0, Character H
Index 1, Character e
Index 2, Character l
Index 3, Character l
Index 4, Character o
Index 5, Character
Index 6, Character W
Index 7, Character o
Index 8, Character r
Index 9, Character l
Index 10, Character d