Java Program to convert a string or char to ASCII value

Computers can only understand numbers, more specifically, binaries (0 or 1). To store or exchange text-based information in computers, we need some kind of character encoding that can encode text data to numbers which can then be represented using binary digits.

ASCII (American Standard Code for Information Exchange) is a character encoding standard developed in the early 60’s for representing and exchanging text-based information in computers. The ASCII character set consists of 128 characters that are represented using 7-bit integers. You can check out the complete ASCII character set here.

This article shows you how to convert a character to ASCII code or get the character from a given ASCII code in Java. The conversion from character to ASCII code or ASCII code to character is done using type casting. Check out the following programs to know more:

Convert character to ASCII code in Java

class CharToAsciiCodeExample {
    public static void main(String[] args) {
        char ch = 'A';
        int asciiValue = ch;  // char is automatically casted to int

        System.out.printf("Ascii Value of %c = %d\n", ch, asciiValue);
$ javac
$ java CharToAsciiCodeExample
Ascii Value of A = 65

Convert ASCII code to character in Java

class AsciiCodeToCharExample {
    public static void main(String[] args) {
        int asciiValue = 97;
        char ch = (char) asciiValue;

        System.out.printf("Character corresponding to Ascii Code %d = %c\n", asciiValue, ch);
$ javac
$ java AsciiCodeToCharExample
Character corresponding to Ascii Code 97 = a