How to Convert Character to String in Java? (3 Different Techniques)

Sometimes, when working with the Character (or char) data type in Java, it is required to convert it to String. In this tutorial, we’ll look at 3 different ways of converting Character to String. These are:

  1. Conversion using String.valueOf(…)
  2. Conversion using Character.toString()
  3. Conversion using String Concatenation

1. String.valueOf(…)

This one is my favorite because it’s easy to remember and is supported for other data types as well. String.valueOf(char c) is a static method which takes a character data type as argument and returns its String representation. It will throw java.lang.NullPointerException if the argument is null. This method should be your preferred way of converting Characters to Strings.

Side note: Other (overloaded) valueOf(...) methods of the String class takes different data types as arguments like double, integer etc. and return a String.

Let’s take a look at an example of how this work.

package com.codeahoy.ex;

public class Main {
    public static void main(String[] args) {
        Character c = 'U';
        
        String str = String.valueOf(c);

        System.out.println(str);
    }
}

Output:

U

2. Character.toString()

Character class overrides the toString() method to provide a convenient way of converting Characters to Strings. Let’s take a look at an example.

package com.codeahoy.ex;

public class Main {
    public static void main(String[] args) {
        Character c = 'U';

        // Do the conversion using toString()
        String str = c.toString();

        System.out.println(str);
    }
}

Output:

U

3. String Concatenation Type Conversion

The concatenation (+) operator is normally used to concatenate two Strings in Java. E.g.

str = s1 + s2

Concatenation operator still works if one of the arguments is of Character type and the compiler will type cast automatically. Let’s see it in action.

package com.codeahoy.ex;

public class Main {
    public static void main(String[] args) {
        Character c = 'A';

        // Conversion using + operator
        String str = "" + c;
        
        System.out.println(str);
    }
}

Output:

A

That’s all. Until next time.

Please leave your comments below and like on Facebook or follow on Twitter to stay up-to-date.

comments powered by Disqus