How to Convert Char to String & String to char in Java

In this tutorial, we will study programs to
  1. To convert a character to String
  2. 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 -
  1. Method 1: Using toString() method
  2. Method 2: Using valueOf() method
  1. //Convert character to String using string method
  2. package com.guru99;
  3. public class CharToString {
  4. public static void main(String[] args)
  5. {
  6. //input character variable
  7. char myChar = 'g';
  8. //Using toString() method
  9. //toString method take character parameter and convert string.
  10. String myStr = Character.toString(myChar);
  11. //print string value
  12. System.out.println("String is: "+myStr);
  13. //we can use other method for valueOf()
  14. //valueOf method take character parameter and convert string.
  15. myStr = String.valueOf(myChar);
  16. ////print string value
  17. System.out.println("String is: "+myStr);
  18. }
  19. }

Output :

String is: g
String is: g

Convert String to char

We can convert a String to char using charAt() method of String class.
  1. //Convert String to Character using string method
  2. package com.guru99;
  3. public class StringToChar {
  4. public static void main(String[] args)
  5. {
  6. //input String
  7. String myStr = "Guru99";
  8. //find string length using length method.
  9. int stringLength =myStr.length();
  10. //for loop start 0 to total length
  11. for(int i=0; i < stringLength;i++)
  12. {
  13. //chatAt method find Position and convert to character.
  14. char myChar = myStr.charAt(i);
  15. //print string to character
  16. System.out.println("Character at "+i+" Position: "+myChar);
  17. }
  18. }
  19. }

Output:

Character at 0 Position: G
Character at 1 Position: u
Character at 2 Position: r
Character at 3 Position: u
Character at 4 Position: 9
Character at 5 Position: 9

No comments:

Post a Comment