Java Program to Print the ASCII values


In this article, we will understand how to print ascii values of characters. This is done by assigning the character to an integer value and printing those integer values.

ASCII stands for American Standard Code for Information Interchange. There are 128 standard ASCII codes, each of which can be represented by a 7-digit binary number: 0000000 through 1111111. Extended ASCII adds an additional 128 characters that vary between computers, programs and fonts.

Below is a demonstration of the same −

Input

Suppose our input is −

Enter a character: s

Output

The desired output would be −

Ascii value of s is 115

Algorithm

Step1- Start
Step 2- Declare a char as my_input
Step 3- Prompt the user to enter a character/ define the character
Step 4- Read the value
Step 5- Assign the character to an integer variable and store it.
Step 6- Display the result
Step 7- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool run button.

import java.util.Scanner;
public class AsciiValue {
   public static void main(String[] args){
      char my_input;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.print("Enter a character: ");
      my_input = my_scanner.next().charAt(0);
      System.out.println("The float values have been defined as " +my_input);
      int ascii_value = my_input;
      System.out.println("The ASCII value of " + my_input + " is: " + ascii_value);
   }
}

Output

Required packages have been imported
A scanner object has been defined
Enter a character: s
The float values have been defined as s
The ASCII value of s is: 115

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class AsciiValue{
   public static void main(String[] args){
      char my_input;
      my_input = 's';
      System.out.println("The character has been defined as " +my_input);
      int ascii_value = my_input;
      System.out.println("The ASCII value of " + my_input + " is: " + ascii_value);
   }
}

Output

The character has been defined as s
The ASCII value of s is: 115

Updated on: 21-Feb-2022

860 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements