Java Program to Find ASCII Value of a character

In this program, you’ll learn to find and display the ASCII value of a character in Java. This is done using type-casting and normal variable assignment operations.

Example: Find ASCII value of a character

  1. public class AsciiValue {
  2. public static void main(String[] args) {
  3. char ch = 'a';
  4. int ascii = ch;
  5. // You can also cast char to int
  6. int castAscii = (int) ch;
  7. System.out.println("The ASCII value of " + ch + " is: " + ascii);
  8. System.out.println("The ASCII value of " + ch + " is: " + castAscii);
  9. }
  10. }

When you run the program, the output will be:

The ASCII value of a is: 97
The ASCII value of a is: 97

In the above program, character a is stored in a char variable, ch. Like, double quotes (" ") are used to declare strings, we use single quotes (' ') to declare characters.

Now, to find the ASCII value of ch, we just assign ch to an int variable ascii. Internally, Java converts the character value to an ASCII value.

We can also cast the character ch to an integer using (int). In simple terms, casting is converting variable from one type to another, here char variable ch is converted to an int variable castAscii.

Finally, we print the ascii value using the println() function.