Java Program to print ASCII value of a Character

In this tutorial, you will learn how to find the ASCII value of a character in Java. Before that, you need to have the knowledge of the following in Java Programming.

ASCII stands for American Standard Code for Information Interchange. It is a 7-bit character set that contains 128 (0 to 127) characters. It represents the numerical value of a character.

Example: ASCII value for character A is 65, B is 66 but a is 97, b is 98, and so on.

There are two ways to find the ASCII value of a character, we will learn both of them.

  1. Variable Assignment
  2. Using Type-Casting

1. Variable Assignment

Java internally converts the character values to ASCII values, we do not require any type of method to do so.

public class AsciiValue    
{  
    public static void main(String[] args)   
    {  
        // character whose ASCII value to be found  
        char ch1 = 'A';  
        char ch2 = 'a';  
        
        //assigning character to int  
        int ascii1 = ch1;  
        int ascii2 = ch2;  
        
        System.out.println("The ASCII value of " + ch1 + " is: " + ascii1);  
        System.out.println("The ASCII value of " + ch2 + " is: " + ascii2);  
    }  
}  

Output:

The ASCII value of A is: 65
The ASCII value of a is: 97


2. Using Type-Casting

Type-casting refers to the casting of one data-type variable to another data type.

public class AsciiValue    
{  
    public static void main(String[] args)   
    {  
        // character whose ASCII value to be found  
        char ch1 = 'A';  
        char ch2 = 'a';  
        
        //casting to int  
        int ascii1 = (int) ch1;  
        int ascii2 = (int) ch2;  
        
        System.out.println("The ASCII value of " + ch1 + " is: " + ascii1);  
        System.out.println("The ASCII value of " + ch2 + " is: " + ascii2);  
    }  
}  

Output:

The ASCII value of A is: 65
The ASCII value of a is: 97


We can also take the user input for character by using the Scanner class and print the ASCII value accordingly as shown in the program below.

import java.util.Scanner;

public class AsciiValue    
{  
    public static void main(String[] args)   
    {  
        Scanner sc = new Scanner(System.in);
        
        // User Input 
        System.out.print("Enter a character: ");  
        char ch = sc.next().charAt(0); 
        
        //assigning to int  
        int ascii1 = ch;  
        
        System.out.println("The ASCII value of " + ch + " is: " + ascii1);  
    }  
}  

Output:

Enter a character: b
The ASCII value of b is: 98