Procedure to Convert Char To String and a String to char in Java ?

  Java Interview Q&A

Dear readers, today we will read in this tutorial char to String and String to char conversion in Java Program in easy way .

Java Program to convert char to String

You can two ways for char to String conversion.
Method 1: Using toString() method
Method 2: Usng valueOf() method

class CharToStringDemo
{
   public static void main(String args[])
   {
      // Method 1: Using toString() method
      char ch = 'a';
      String str = Character.toString(ch);
      System.out.println("String is: "+str);
 
      // Method 2: Using valueOf() method
      String str2 = String.valueOf(ch);
      System.out.println("String is: "+str2);
   }
}

Output:

String is: a
String is: a

Java Program to Converting String to Char

You can using charAt() method of String class. to convert string to char.

class StringToCharDemo
{
   public static void main(String args[])
   {
      // Using charAt() method
      String str = "Hello";
      for(int i=0; i<str.length();i++){
        char ch = str.charAt(i);
        System.out.println("Character at "+i+" Position: "+ch);
      } 
   }
}

Output:

Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o

Read here complete . JAVA Program Tutorial

LEAVE A COMMENT