Check Alphabet/Digit/Special Character in Java

Check whether a character is an alphabet, digit, or special character.

BeginnerModule 2: Conditional ProgramsExample 3 of 20
check-alphabet-digit-special-character.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 if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
11 System.out.println(ch + " is an Alphabet");
12 } else if (ch >= '0' && ch <= '9') {
13 System.out.println(ch + " is a Digit");
14 } else {
15 System.out.println(ch + " is a Special Character");
16 }
17
18 sc.close();
19 }
20}

Output

Enter a character: 9
9 is a Digit

What's going on

We use character ranges to classify the input as alphabet, digit, or special symbol.