English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to find and display the ASCII value of a character in Java. This is done through type conversion and regular variable assignment operations.
public class AsciiValue { public static void main(String[] args) { char ch = 'a'; int ascii = ch; //You can also convert char to int int castAscii = (int) ch; System.out.println("ASCII value ", + ch + " = " + ascii); System.out.println("ASCII value ", + ch + " = " + castAscii); } }
When running this program, the output is:
ASCII value a = 97 ASCII value a = 97
In the above program, the character a is stored in the char variable ch. Just as we use double quotes ("") to declare a string, we use single quotes ('') to declare a character.
Now, to find the ASCII value of ch, we just need to assign ch to an int variable ascii. Internally, Java will convert the character value to an ASCII value.
We can also use (int) to convert the character ch to an integer. In simple terms, the conversion is the process of changing a variable from one type to another, here the char variable ch is converted to the int variable castAscii.
Finally, we use the println() function to print the ASCII value.