Check whether a character is an alphabet or not in Java
Understanding Alphabets
An alphabet is any letter from A to Z (both uppercase and lowercase). Any other character is not considered an alphabet.
We will explore three different methods to check whether a character is an alphabet or not in Java.
Method 1: Using if-else
This method checks if the character falls within the range of alphabets.
import java.util.Scanner; public class AlphabetCheck { public static void checkAlphabet(char ch) { 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"); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a character: "); char ch = scanner.next().charAt(0); checkAlphabet(ch); scanner.close(); } }
Output: A is an alphabet
Method 2: Using ASCII Values
This method checks the ASCII values of the character.
import java.util.Scanner; public class AlphabetCheckASCII { public static void checkAlphabet(char ch) { if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) { System.out.println(ch + " is an alphabet"); } else { System.out.println(ch + " is not an alphabet"); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a character: "); char ch = scanner.next().charAt(0); checkAlphabet(ch); scanner.close(); } }
Output: 1 is not an alphabet
Method 3: Using a Function
This method defines a function to check if a character is an alphabet.
import java.util.Scanner; public class AlphabetCheckFunction { public static boolean isAlphabet(char ch) { return ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')); } public static void checkAlphabet(char ch) { if (isAlphabet(ch)) { System.out.println(ch + " is an alphabet"); } else { System.out.println(ch + " is not an alphabet"); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a character: "); char ch = scanner.next().charAt(0); checkAlphabet(ch); scanner.close(); } }
Output: z is an alphabet