2 ways to Convert ASCII to String in Java

In this post, I will be sharing how to convert ASCII to equivalent String values in Java. There are two ways to achieve our goal.

1. Using Character.toString() [Recommended]
2. Using String.valueOf()

Read Also:   Java Isogram

Java Program: Convert ASCII to String

1. Using Character.toString()


In the below example, we have an array of ASCII values. We are performing the below steps:
a. Converting ASCII values into corresponding char values.
b. Transforming those char values to string using the toString() method of Character class.

 public class AsciiToStringProgram {
    public static void main(String args[]) {
        
      int[] numbers = {65, 75, 85, 97, 105, 115};
      
      String str = null;
      
      for (int num : numbers) {
          // Converting ascii value to String
          str = Character.toString( (char) num);
          System.out.println(str);
      }
    }
}

Output:
A
K
U
a
i
s


2. Using String.valueOf()


In the below example, we are using Character.toChars(int) method to convert an array of ASCII values to static char[] in Java. Then, we are converting static char[] to string using String.valueOf() method.

 public class AsciiToStringProgram2 {
    public static void main(String args[]) {
        
      int[] numbers = {65, 66, 97, 98};
      
      String str = null;
      
      for (int num : numbers) {
          // Converting ascii value to String
          str = String.valueOf(Character.toChars(num));
          System.out.println(str);
      }
    }
}

Output:
A
B
a
b


Perofrmance wise Character.toString((char) num) is faster than String.valueOf(Character.toChars(num)).

That's all for today, please mention in the comments in case you have any questions related to convert ASCII to String in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry