Java Program to print the ASCII value of a character

Get a character from user and display the corresponding ASCII value

Sample Input 1:

A

Sample Output 1:

65

Sample Input 2:

J

Sample Output 2:

74

Program or Solution

				
			
					
import java.util.*;
class Ascii
{
 
    public static void main(String args[])
    {
       char ch;
       int ascii;
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter The Character:");
       ch=sc.next().charAt(0);
       ascii=(int)ch;
       System.out.println("Equivalent Ascii Value:"+ascii);
    }

}


			
				
			

Program Explanation

The Scanner class, which is part of the java.util package, is used to get user input. To use the Scanner class, create an object of the class and call any of the methods listed in the documentation for the Scanner class. The next() method, which is used to read character, are used in our example.

charat(0) returns first character, if user enters multiple character. 

The Input character  is stored in the variable ch and converted as integer using (int) which returns the ASCII value of the characters.