Find the ASCII value of a character in Java

Hello everyone! I am here to explain how to find an ASCII value of a character in Java. To represent alphabets in the form of numerical values, ASCII values can be used. In order to find the ASCII value of a character, here I am using the typecasting method. The typecast method is used to convert a variable from one type to another type.

Typecasting method to find the ASCII value of a character in Java

import java.util.*;
public class Main
{
  public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        char character=s.next().charAt(0);
        System.out.println("ascii value of "+character+" is "+(int)character);
    
  }
}

In order to find the ASCII value of a character,  we have to typecast the variable which stores a character by an integer. For example, “(int)character”.

In my above program, use Scanner class to read a character of your own. You can access Scanner class by importing java.util.* package. And the argument passed is “System.in” in order to read input from the keyboard. Then declaring a variable-name as a character, stores value of type character. And you can read whatever character. And the declared variable stores the character. Finally, printing the ASCII value by typecasting it as “(int)variable-name”.

This is how we can find the ASCII value of a character in an easy way. Hope this explanation is helpful. And you can even declare an integer variable and then assign the character to it. This method might even be useful to find the ASCII value of a character. And if you are using this method Then there is no need for the Typecasting method.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *