This post will discuss how to convert a char to its ASCII value, and vice versa, in Java.

1. Using Casting or Implicit Conversion

A simple way to convert a char to its ASCII value is to cast the char as an int, which will return the ASCII value of the char. Casting is an explicit conversion from one data type to another. Here’s a Java program that demonstrates this:

Download  Run Code

 
Note that casting char to int is redundant, although it improves readability. We can take advantage of the implicit conversion by the compiler when a character value is assigned to an integer. This implicit unboxing works since the compiler can determine the result of this expression. For example:

Download  Run Code

 
To do the opposite, i.e., get the corresponding char from the ASCII value in Java, we can simply cast it into a char. This will not result in any loss of precision if the integer represents the ASCII range of characters.

Download  Run Code

2. Using codePointAt() method

Alternatively, we can use the codePointAt(int) method of the String class to get the ASCII value of a char in a string. Here is an example of using this method for a single char:

Download  Run Code

 
The Character class also provides the static method codePointAt(char[], int), which can obtain the ASCII value of a char as follows:

Download  Run Code

 
To get the corresponding character from the ASCII value in Java, we can use the Character.toChars(int) method. This method converts the specified char to its UTF-16 representation and returns a char array. For example:

Download  Run Code

3. Using getBytes() method

If we need to convert each character of a string to ASCII, we can encode the string into a sequence of bytes using the getBytes() method of the String class, which results in a new byte array. To get the ASCII value for a single char, we can convert the char to a string first using the String.valueOf(char) method, then call the getBytes() method on the string, and access the first index like below:

Download  Run Code

That’s all about converting a char to its ASCII value, and vice versa, in Java.