Introduction

Java Program to Find ASCII Value of a Character

A Java program to find and print the ASCII value of a character.

Problem Description

Write a Java program that takes a character as input (or uses a hardcoded character) and prints its ASCII value.

Code

AsciiValue.java
public class AsciiValue {
    public static void main(String[] args) {
        char ch = 'a';
        int ascii = ch;
        // You can also cast char to int
        int castAscii = (int) ch;

        System.out.println("The ASCII value of " + ch + " is: " + ascii);
        System.out.println("The ASCII value of " + ch + " is: " + castAscii);
    }
}

Output

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

Explanation

  1. char ch = 'a';: Declares a character variable ch and assigns it the value 'a'.
  2. int ascii = ch;: Assigns the character value to an integer variable. Java automatically promotes char to int, which results in the ASCII value.
  3. (int) ch: Explicitly casts the character to an integer, which also yields the ASCII value.

Try Yourself

Test your understanding of characters and ASCII values.

  1. Find Value of 'Z': Change the character to 'Z' and find its ASCII value.
  2. Digit ASCII: Find the ASCII value of the character '9'. Is it the number 9?
  3. Reverse It: Create an integer variable int n = 66; and cast it to char. What letter do you get?
  4. Math with Char: What happens if you do System.out.println('a' + 1);? Try it.
  5. Brain Twister: Find the ASCII value of the space character ' '.