Java Program to Find ASCII Value of a character .

Write a program to find ASCII value.

public class AsciiValueCharacter {

    public static void main(String[] args) {

        char ch = 'a';
        int ascii = ch;
        // You can also cast char to int
        int castAsciichar = (int) ch;

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

Output

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

In the above program, we define character variable using char keyword and variable ch is having value of ‘a’. A character is defined using single quote(‘ ‘ ).

Obviously, ASCII value of any character will be an int, so we need to define that in a int variable ie. int ascii = ch . After that, JVM internally converts the character value to its corresponding ASCII value.

the line int castAsciichar = (int) ch is purely casting concept. In other words, Casting is a concept of converting one type into other type. For instance, char variable is converted to int type here.

Leave a Reply