Today we will look into java char to String program. We will also learn how to convert String to a char array.

Java char to String

Before we look into java char to String program, let’s get to the basic difference between them.

  1. char is a primitive data type whereas String is a class in java.
  2. char represents a single character whereas String can have zero or more characters. So String is an array of chars.
  3. We define char in java program using single quote (‘) whereas we can define String in Java using double quotes (“). Since String is a special class, we get this option to define string using double quotes, we can also create a String using new keyword.

Java char to String example

We can use String.valueOf(char c) or Character.toString(char c) to convert char to string. Below is the example program showing how to use these methods to convert char to string.

java.lang.Character is the wrapper class for primitive char data type. Character.toString(char c) internally calls String.valueOf(char c) method, so it’s better to use String class function to convert char to String.

Output of the above program is shown in below image.

java-char-to-string

Java String to char array

Since String is an array of char, we can convert a string to the char array. String class also has a method to get the char at a specific index. Let’s look at a simple program to convert String to a char array.

To get the char from a String object, we can use chatAt(int index)method. Whereas toCharArray() returns the char array of the String.

Here we are using Arrays.toString(char[] ca) method to print the char array in readable format.

Output of the above program is shown below.

java-string-to-char-array

That’s all for the char to String and String to char array conversion.

Reference: Character API Doc

By admin

Leave a Reply