Java Program to Find ASCII Value of a character

63
Java Program to Find ASCII Value of a character
Advertisement

In this post, you will learn about finding and displaying ASCII value for any character. The American Standard Code for Information Interchange (ASCII) is a widely used character encoding scheme that assigns unique numeric values to various characters. In this blog post, we will delve into a simple Java program that allows you to find the ASCII value of a character.

Understanding ASCII:

ASCII represents characters using a 7-bit binary code, allowing a total of 128 unique characters to be encoded. The encoding assigns each character a numeric value between 0 and 127. Common ASCII values include alphabets (both uppercase and lowercase), digits, punctuation marks, and control characters.

Java Program to Find ASCII Value:

Let’s dive into the Java program that helps us find the ASCII value of a character. Here’s the code:

Java – ASCII Value Program
import java.util.Scanner;

public class ASCIIValueFinder {
    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a character: ");
        char ch = scanner.next().charAt(0);
        
        int asciiValue = (int) ch;
        
        System.out.println("The ASCII value of " + ch + " is " + asciiValue);
    }
}

compile and run it. When prompted, enter a character of your choice. The program will then display the corresponding ASCII value.

Output
Enter a character: A
The ASCII value of A is 65

Explanation:

  1. We begin by importing the java.util.Scanner class, which allows us to read input from the user.
  2. In the main method, we create a new Scanner object to capture user input.
  3. We prompt the user to enter a character using the System.out.print statement.
  4. The next line of code char ch = scanner.next().charAt(0); reads a string input from the user and retrieves the first character using the charAt(0) method. We store this character in the variable ch.
  5. To find the ASCII value, we cast the character ch to an integer using (int) ch and assign the result to the variable asciiValue.
  6. Finally, we display the ASCII value to the user using the System.out.println statement.

In this blog post, we explored a simple Java program that allows us to find the ASCII value of a character. Understanding ASCII values is essential in various scenarios, such as working with character-based algorithms, encryption techniques, and networking protocols. By implementing this program, you have gained a valuable tool for exploring the world of character encoding in Java. Remember to experiment further and build upon this foundation to enhance your programming skills. Happy coding!

Latest Posts: