In this java program, we will learn about how to check whether a given character is an alphabet or not using if-else statement and isAlphabetic method.
When we store a character in a variable of data type char, the ASCII value of character is stored instead of that character itself. The integer value corresponding to a character is know as it's ASCII value. The ASCII value of uppercase alphabets(A to Z) are from 65 to 90 whereas the ASCII value of lowercase alphabets(a to z) are from 97 to 122.
For Example:
The ASCII value of 'A' and 'a' is 65 and 97 respectively.
A character and it's ASCII value can be used interchangeably. If any expression contains a character then it's corresponding ASCII value is used in expression. When we compare a char variable between 'a' to 'z' and 'A' to 'Z', the variable is compared with the ASCII value of the alphabets 97 to 122 and 65 to 90 respectively.
To understand this java program, you should have understanding of the following Java programming concepts:
Java Program to Check Alphabet by Comparing ASCII values
public class AlphabetCheck1 { public static void main(String[] args) { char c; Scanner scanner = new Scanner(System.in); System.out.println("Enter a Character"); c = scanner.next().charAt(0); if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { System.out.println(c + " is an Alphabet"); } else { System.out.println(c + " is not an Alphabet"); } } }Output
Enter a Character 4 4 is not an Alphabet Enter a Character T T is an Alphabet
Java Program to Check Alphabet using isAlphabetic() Method
public class AlphabetCheck2 { public static void main(String[] args) { char c; Scanner scanner = new Scanner(System.in); System.out.println("Enter a Character"); c = scanner.next().charAt(0); if (Character.isAlphabetic(c)) { System.out.println(c + " is an Alphabet"); } else { System.out.println(c + " is not an Alphabet"); } } }Output
Enter a Character d d is an Alphabet Enter a Character @ @ is not an Alphabet
In above java program, we used isAlphabetic() method of the Character class. This method returns true if the given character is an alphabet otherwise it returns false.