C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Find ASCII value of a character - Java Program

import java.util.Scanner;

 

public class ASCIIValue {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        // Taking character input from user

        System.out.print("Enter any character: ");

        char ch = sc.next().charAt(0);

 

        // Typecasting char to int gives ASCII value

        int ascii = (int) ch;

 

        // Displaying ASCII value

        System.out.println("The ASCII value of '" + ch + "' is: " + ascii);

 

        sc.close();

    }

}

Output

 
OUTPUT 1:
Enter any character: A
The ASCII value of 'A' is: 65

OUTPUT 2:
Enter any character: z
The ASCII value of 'z' is: 122

Explanation

Step 1 — Take a Character as Input

char ch = sc.next().charAt(0);

  • next() reads a string
  • charAt(0) extracts the first character
  • We store it in a char variable ch

Step 2 — Convert char to int

int ascii = (int) ch;

  • A character in Java internally represents a Unicode value
  • Casting it to int gives its ASCII (same for standard characters A–Z, a–z, 0–9, symbols)

Step 3 — Print the ASCII Value

System.out.println("The ASCII value of '" + ch + "' is: " + ascii);