This Java code example demonstrates how to find and print the ASCII value of a given character. The ASCII (American Standard Code for Information Interchange) value is a numerical representation of characters used in computers and other devices. This example highlights the use of input handling, character manipulation, and basic type casting in Java.
import java.util.Scanner;
class AsciiValueOfCharacter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for a character input
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
// Get ASCII value of the character
int asciiValue = (int) ch;
// Print the ASCII value
System.out.println("The ASCII value of '" + ch + "' is: " + asciiValue);
scanner.close();
}
}
public static void main(String[] args)
The main method executes the program and contains the logic for getting and printing the ASCII value of a character.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for a character input
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
// Get ASCII value of the character
int asciiValue = (int) ch;
// Print the ASCII value
System.out.println("The ASCII value of '" + ch + "' is: " + asciiValue);
scanner.close();
}
Scanner scanner = new Scanner(System.in);
creates a Scanner
object to read input from the user.System.out.print("Enter a character: ");
prompts the user to enter a character.char ch = scanner.next().charAt(0);
reads the next token of input as a string and extracts the first character from it.int asciiValue = (int) ch;
casts the character ch
to an integer, which gives its ASCII value.System.out.println("The ASCII value of '" + ch + "' is: " + asciiValue);
prints the character and its ASCII value.scanner.close();
closes the Scanner
object to free up resources.