In this post we’ll see Java programs for char to String and String to char conversions.
Converting char to String in Java
For converting char to String you can use any of the following methods.
- Character.toString(char c)- Returns a String object representing the specified char.
- String.valueOf(char c)- Returns the string representation of the char argument.
Java program
public class CharToString { public static void main(String[] args) { char ch = 'x'; // Using toString() method String str = Character.toString(ch); System.out.println("Converted String - " + str); // Using valueOf() method str = String.valueOf(ch); System.out.println("Converted String - " + str); } }
Output
Converted String - x Converted String – x
Converting String to char in Java
For converting String to char you can use one of the following options.
- Using charAt(int index) method of the String class. This method returns the char value at the specified index.
- Using toCharArray() method of the String class you can convert the String to char array and then get the char out of that array using the array index.
public class StringToChar { public static void main(String[] args) { String str = "Test"; // getting the 3rd char in the String // index is 0 based char ch = str.charAt(2); System.out.println("Character is- " + ch); // By getting char array System.out.println("----------------"); char[] charArr = str.toCharArray(); for(char c : charArr) { System.out.println("Character is- " + c); } } }
Output
Character is- s ---------------- Character is- T Character is- e Character is- s Character is- t
That's all for this topic Converting Char to String And String to Char in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment