Write a Java program to check whether a character is an alphabet or not using an if-else statement with an example. The If condition checks whether the user entered character is between a to z or A to Z. If it is True, it is an Alphabet; otherwise, it is not an alphabet.
import java.util.Scanner; public class CharIsAlphabet1 { private static Scanner sc; public static void main(String[] args) { char ch; sc= new Scanner(System.in); System.out.print("Please Enter any Character = "); ch = sc.next().charAt(0); 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"); } } }
Check the Digit
Please Enter any Character = 9
9 is Not an Alphabet
Java Program to check whether a character is Alphabet or Not using conditional operator
import java.util.Scanner; public class CharIsAlphabet2 { private static Scanner sc; public static void main(String[] args) { char ch; sc= new Scanner(System.in); System.out.print("Please Enter any Character = "); ch = sc.next().charAt(0); String result = ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) ? ch + " is an Alphabet" : ch + " is Not"; System.out.println(result); } }
Please Enter any Character = m
m is an Alphabet
Please Enter any Character = .
. is Not
In Java, we have an isAlphabetic character function that checks whether the given character is an alphabet or not. And we use the same.
import java.util.Scanner; public class CharIsAlphabet3 { private static Scanner sc; public static void main(String[] args) { char ch; sc= new Scanner(System.in); System.out.print("Please Enter any Letter = "); ch = sc.next().charAt(0); if(Character.isAlphabetic(ch)) { System.out.println(ch + " is an Alphabet"); } else { System.out.println(ch + " is Not"); } } }
Please Enter any Letter = K
K is an Alphabet
Please Enter any Letter = *
* is Not
Each alphabet is associated with an ASCII code. This Java example checks the given characters ASCII value is between 65 to 90 (A to Z) or 97 to 122 (a to z).
import java.util.Scanner; public class CharIsAlphabet4 { private static Scanner sc; public static void main(String[] args) { char ch; sc= new Scanner(System.in); System.out.print("Please Enter any Letter = "); ch = sc.next().charAt(0); if((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) { System.out.println(ch + " is an Alphabet"); } else { System.out.println(ch + " is Not"); } } }
Please Enter any Letter = j
j is an Alphabet
Please Enter any Letter = 1
1 is Not