Java Program to Check Whether a Character is an Alphabet
An alphabet character is a letter from A to Z or a to z. Digits such as 7 and symbols such as @ or # are not alphabets.
In Java a char is stored as a number (its Unicode value), and the letters have consecutive values: 'A' is 65 to 'Z' 90, and 'a' is 97 to 'z' 122. That lets us compare characters with >= and <=.
1. Check Alphabet Using if-else
A character is an alphabet if it lies in the range 'a' to 'z' or in the range 'A' to 'Z'.
public class AlphabetCheck {
public static void main(String[] args) {
char[] characters = {'S', '@', '7', 'j'};
for (char ch : characters) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
System.out.println(ch + " is an alphabet.");
} else {
System.out.println(ch + " is not an alphabet.");
}
}
}
}
S is an alphabet. @ is not an alphabet. 7 is not an alphabet. j is an alphabet.
2. Check Alphabet with User Input
Scanner has no method to read a single character, so the program reads a word with next() and takes its first character with charAt(0).
import java.util.Scanner;
public class AlphabetCheckInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
scanner.close();
boolean isAlphabet = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
System.out.println(ch + (isAlphabet ? " is an alphabet." : " is not an alphabet."));
}
}
Enter a character: S S is an alphabet.
Enter a character: 7 7 is not an alphabet.
Enter a character: # # is not an alphabet.
3. Check Alphabet Using Character.isLetter()
The Character class has ready-made methods for this. Character.isLetter() returns true for any letter, including letters from other languages such as é. Use the range check above if you need only the English letters A–Z.
public class AlphabetIsLetter {
public static void main(String[] args) {
char[] characters = {'k', 'Q', '5', '$', 'é'};
for (char ch : characters) {
System.out.println(ch + " -> isLetter: " + Character.isLetter(ch)
+ ", isDigit: " + Character.isDigit(ch));
}
}
}
k -> isLetter: true, isDigit: false Q -> isLetter: true, isDigit: false 5 -> isLetter: false, isDigit: true $ -> isLetter: false, isDigit: false é -> isLetter: true, isDigit: false
4. Summary
- Characters are stored as numbers, so you can compare them with
>=and<=. - A character is an English alphabet if it is between
'a'and'z'or between'A'and'Z'. - Read one character from the keyboard with
scanner.next().charAt(0). Character.isLetter()also accepts letters from other alphabets.