In this tutorial, we will study programs to
- To convert a character to String
- To convert a String to character
Convert Char To String
There are multiple ways to convert a Char to String in Java. In fact, String is made of Character array in Java. Char is 16 bit or 2 bytes unsigned data type.
We can convert String to Character using 2 methods -
Method 1: Using toString() method
Program:
public class CharToString_toString
{
public static void main(String[] args)
{
//input character variable
char myChar = 'g';
//Using toString() method
//toString method take character parameter and convert string.
String myStr = Character.toString(myChar);
//print string value
System.out.println("String is: " + myStr);
}
}
{
public static void main(String[] args)
{
//input character variable
char myChar = 'g';
//Using toString() method
//toString method take character parameter and convert string.
String myStr = Character.toString(myChar);
//print string value
System.out.println("String is: " + myStr);
}
}
Output:
String is: g
Method 2: Using valueOf() method
Program:
public class CharToString_valueOf
{
public static void main(String[] args)
{
char myChar = 'g';
//valueOf method take character parameter and convert string.
String myStr = String.valueOf(myChar);
////print string value
System.out.println("String is: " + myStr);
}
}
Output:
String is: g
Convert String to char
We can convert a String to char using charAt() method of String class.
Program:
//Convert String to Character using string method
public class StringToChar
{
public static void main(String[] args)
{
//input String
String myStr = "java100";
//find string length using length method.
int stringLength =myStr.length();
//for loop start 0 to total length
for(int i=0; i < stringLength;i++)
{
//chatAt method find Position and convert to character.
char myChar = myStr.charAt(i);
//print string to character
System.out.println("Character at "+i+" Position: "+myChar);
}
}
}
Output:
Character at 0 Position: j
Character at 1 Position: a
Character at 2 Position: v
Character at 3 Position: a
Character at 4 Position: 1
Character at 5 Position: 0
Character at 6 Position: 0