Wednesday, December 22, 2021

Converting Char to String And String to Char in Java

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.

  1. Character.toString(char c)- Returns a String object representing the specified char.
  2. 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.

  1. Using charAt(int index) method of the String class. This method returns the char value at the specified index.
  2. 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

  1. Convert Numbers to Words Java Program
  2. Converting Enum to String in Java
  3. Convert String to float in Java
  4. How to Iterate a HashMap of ArrayLists of String in Java
  5. Find Duplicate Characters in a String With Repetition Count Java Program

You may also like-

  1. How to Read Excel File in Java Using Apache POI
  2. Compress And Decompress File Using GZIP Format in Java
  3. Find Largest and Second Largest Number in Given Array Java Program
  4. Difference Between Two Dates in Java
  5. Map.Entry Interface in Java
  6. Java Collections Interview Questions And Answers
  7. Type Casting in Java With Conversion Examples
  8. Spring Web MVC Tutorial

No comments:

Post a Comment