ASCII value of character

The term ASCII (American Standard Code for Information Interchange) refers to a defined character encoding. It assigns certain codes to characters such as letters, digits and punctuation marks. The ASCII code is used to specify how the characters are displayed by electronic devices – such as PCs or smartphones. This is an important part of many programming operations.

Code Example

import java.util.Scanner;

class AsciiValue {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        char character;
        int asciiValue;

        System.out.print("Please enter character: ");
        character = reader.next().charAt(0);
        reader.close();

        asciiValue = (int) character;
        System.out.println("ASCII value of the character "
                + character + " is: " + asciiValue);
    }
}
Output
Please enter character: F
ASCII value of the character F is: 70

Code Explanation

import java.util.Scanner; imports the Scanner class from the java.util package. This class is used to read user input from the console.

class AsciiValue declares a class named AsciiValue.

public static void main(String[] args) is the main method of the program where the execution starts. It takes an array of strings as a parameter (although it is not used in this program).

The following lines declare variables:

Scanner reader = new Scanner(System.in);
char character;
int asciiValue;

Here, reader is an instance of the Scanner class that is used to read user input. character is a char variable to store the character entered by the user, and asciiValue is an int variable to store the corresponding ASCII value.

System.out.print("Please enter character: "); displays a prompt message asking the user to enter a character.

character = reader.next().charAt(0); reads the next user input as a string using the next() method of the Scanner class, and then uses the charAt(0) method to extract the first character from the entered string. The character is stored in the character variable.

reader.close(); closes the Scanner object to release system resources after reading the user input.

asciiValue = (int) character; assigns the ASCII value of the character to the asciiValue variable. The (int) casting is used to convert the character to its corresponding integer ASCII value.

The following line prints the calculated ASCII value:

System.out.println("ASCII value of the character " + character + " is: " + asciiValue);

The System.out.println() statement displays the ASCII value of the character entered by the user. The value is concatenated with other strings to form the output message.