Character to ASCII in Java

Convert a character to its ASCII code.

BeginnerModule 1: Basic Java ProgramsExample 18 of 20
character-to-ascii.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter a character: ");
8 char ch = sc.next().charAt(0);
9
10 int code = (int) ch;
11 System.out.println("ASCII code of " + ch + " = " + code);
12
13 sc.close();
14 }
15}

Output

Enter a character: a
ASCII code of a = 97

What's going on

Again, we cast the char to int to see its numeric code.