June 22, 2022

Convert Char to String And String to Char in Java

In your Java program you may have a requirement to convert a char to String or to convert a String to char. This post shows different options to do these conversions.

Convert char to String in Java

1. For converting char to String in Java there is a toString() method in the Character class.

If there is a Character class object then you can call toString() method on that object.

There is another static toString(char c) method which returns a String representation of the passed char.

public class CharStrConversion {
  public static void main(String[] args) {
    char ch = 'a';
    String str = Character.toString(ch);
    System.out.println("Converted String - " + str);
  }
}
Output
Converted String – a

2. Another option for converting char to String in Java is to use String.valueOf(char c) method that returns the string representation of the char argument.

public class CharStrConversion {
  public static void main(String[] args) {
    char ch = 'a';
    String str = String.valueOf(ch);
    System.out.println("Converted String - " + str);
  }
}
Output
Converted String – a

Convert String to char in Java

For converting String to char in Java you can use one of the following methods of the String class.

  • charAt(int index)- Returns the char value at the specified index.
  • toCharArray()- Converts this string to a new character array. Then from that array you can get the required char using the index.
public class StrCharConversion {
  public static void main(String[] args) {
    String str = "Hello";
    // to get the 5th char (index starts from 0)
    char ch = str.charAt(4);
    System.out.println("Character is- " + ch);
    // Using toCharArray
    char[] charArr = str.toCharArray();
    ch = charArr[1];
    System.out.println("Character is- " + ch);
  }
}
Output
Character is- o
Character is- e

That's all for the topic Convert Char to String And String to Char in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment