In this program, we are going to see whether a user given character is an alphabet or not. To determine the type of character, we have two different approaches:
- Using ASCII value range
- Using Character class
See also: Find ASCII value of a character
Using ASCII value range
To check if it is an alphabet or not we only need to check its ASCII value range. If it is an alphabet then it’s ASCII value range should be within 65 (A) – 90 (Z) or 97 (a) – 122 (z).
Program
import java.util.Scanner; public class AlphabetOrNot { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter any caracter : "); char c = scanner.next().charAt(0); if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { System.out.println(c + " is A ALPHABET."); } else { System.out.println(c + " is NOT A ALPHABET."); } } }
Output
Enter any character : x
x IS A ALPHABET.
Using Character class
Java has built-in wrapper class Character available in java.lang package. Here we are using isAlphabetic() static method available in Character class to determine whether the given character is an alphabet or not.
Program
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter any character : "); char ch = scanner.next().charAt(0); // Using character static method if (Character.isAlphabetic(ch)) { System.out.println(ch + " IS A ALPHABET."); } else { System.out.println(ch + " IS NOT A ALPHABET."); } } }
Output
Enter any character : x
x IS A ALPHABET.