Friday 7 April 2017

Convert Char to String in Java

Sometimes we have to convert char to String in java program. Here we will look into different methods you can convert character to string in java. We will also learn how to convert char array to String using different methods.

public class CharToStringJava {

 public static void main(String[] args) {

  // char to string
  char c = 'a';
  String str = String.valueOf(c);

  // using Character class
  str = Character.toString(c);

  // another way
  str = new Character(c).toString();
  // string concatenation - worst performance
  str = "" + c;
  
  // char array to string
  char[] ca = { 'a', 'b', 'c' };
  str = String.valueOf(ca);
  // recommended way
  str = new String(ca);

 }

}

String.valueOf(char c)

This is the most efficient method to convert char to string. You should always use this method and this is the recommended way to convert character to string in java program.

Character.toString(c)



This method internally calls String.valueOf(c), so there is no difference between this one. You can use this too if you are already using Character class in your code.

new Character(c).toString();

This is another way, however not recommended because we are creating a Character unnecessarily.

String concatenation

str = "" + c; is the worst way to convert char to string because internally it’s done by new StringBuilder().append("").append(c).toString() that is slow in performance.
Let’s look at the two methods to convert char array to string in java program.

String constructor

You can use String(char[] value) constructor to convert char array to string. This is the recommended way.

String.valueOf(char[] data)

String valueOf method is overloaded and there is one that accepts character array. Internally this method calls the String constructor, so it’s same as above method.
That’s all for converting char to string and char array to string in java.

No comments:

Post a Comment

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...