Java Program to Find ASCII Value of a Character

In the previous article we have discussed about Java Program to Display Character

In this article we are going to see how to print/display  the ASCII value  of any character using Java

Java Program to Find ASCII Value of a Character

Every character which are available have different integer values which is also known as ASCII codes. So we are going to convert any character to its corresponding ASCII value.

Let’s see different ways to achieve it.

Method-1: Java Program to Find ASCII Value of a Character By Using TypeCasting

Approach:

  • Declare a character variable c.
  • Prompt the user to enter a character as input.
  • Convert that input character to its corresponding digit by using (int) followed by the character variable.(i.e Typecasting char to int)
  • Either we can store that converted ASCII value in an new variable or we can simply print the output.

Program:

import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        //creating object of Scanner class 
        Scanner inp=new Scanner(System.in);
        System.out.print("Enter the character: ");
        // taking input from user.
        char c= inp.next().charAt(0);
        System.out.println("Result: "+(int)c);
    }
 }
Output:

Enter the character: *
Result: 42

Method-2: Java Program to Find ASCII Value of a Character By Assigning Character to an Integer Variable

Approach:

  • Take an integer variable c.
  • By default when we assign any character variable to it, it automatically convert it to its corresponding ASCII value and store that value into c.
  • Print the result.

Program:

import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        //creating object of Scanner class 
        Scanner inp=new Scanner(System.in);
        System.out.print("Enter the character: ");
        // taking input from user and store it as an integer.
        int c= inp.next().charAt(0);
        System.out.println("Result: "+c);
    }
}
Output:

Enter the character: *
Result: 42

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Related Java Programs: