In this short tutorial, we’ll see how to get the ASCII value of a character and convert an ASCII value to its character equivalent in Java.
2. Get the ASCII Value of a Character
To get the ASCII value of a character in Java, we can use explicit casting. Additionally, we can get the ASCII value of a character in a string.
2.1. Use Casting
To get the ASCII value of a character, we can simply cast our char as an int:
char c = 'a'; System.out.println((int) c);
And here is the output:
Remember that char in Java can be a Unicode character. So our character must be an ASCII character to be able to get its correct ASCII numeric value.
2.2. Character Inside a String
If our char is in a String, we can use the charAt() method to retrieve it:
String str = "abc"; char c = str.charAt(0); System.out.println((int) c);
3. Getting the Character of an ASCII Value
Simply put, we can convert an ASCII value to its equivalent char by casting:
int value = 65; char c = (char) value; System.out.println(c);
Here’s the output of the code:
Notably, we need to supply an integer within the ASCII value range (0–127) to get the corresponding ASCII character. Any integer outside the ASCII range won’t return null, but a character representation of that integer value in the Unicode character set.
In this article, we learned how to get the ASCII value of a character in Java. Also, we saw how to get the character of an ASCII value.