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
- Method 2: Using valueOf() method
- //Convert character to String using string method
- package com.guru99;
- public class CharToString {
- 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);
- //we can use other method for valueOf()
- //valueOf method take character parameter and convert string.
- myStr = String.valueOf(myChar);
- ////print string value
- System.out.println("String is: "+myStr);
- }
- }
Output :
String is: g String is: g
Convert String to char
We can convert a String to char using charAt() method of String class.
- //Convert String to Character using string method
- package com.guru99;
- public class StringToChar {
- public static void main(String[] args)
- {
- //input String
- String myStr = "Guru99";
- //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: 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