Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

Converting Char to String And String to Char in Java

$
0
0

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!


Related Topics

  1. Converting Numbers to Words - Java Program
  2. Converting Enum to String in Java
  3. Converting String to float - Java Program
  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 -

>>>Go to Java Programs Page


Viewing all articles
Browse latest Browse all 938

Trending Articles