This program is much similar to the previous one but here we are checking whether the given character is an alphabet, digit or a special character.
To determine the type of character, we have two different approaches:
- Using ASCII value range
- Using Character class
Using ASCII value range
Here first we are checking whether the given character is an alphabet or not. If not then check in range 48 (0) to 57 (9) for digit, if it is neither alphabet nor digit then it is absolutely a special character.
See how it is working
Program
import java.util.Scanner; public class AlphabetDigitSpecial { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter any caracter : "); char ch = scanner.next().charAt(0); if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { System.out.println(ch + " is A ALPHABET."); } else if(ch >= '0' && ch <= '9') { System.out.println(ch + " is A DIGIT."); } else { System.out.println(ch + " is A SPECIAL CHARACTER."); } } }
Output
Enter any character : @
@ is A SPECIAL CHARACTER.
Using ASCII value range
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 and isDigit() static method is used to check if it is a digit 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 caracter : "); char ch = scanner.next().charAt(0); // Using character class if (Character.isAlphabetic(ch)) { System.out.println(ch + " is A ALPHABET."); } else if (Character.isDigit(ch)) { System.out.println(ch + " is A DIGIT."); } else { System.out.println(ch + " is A SPECIAL CHARACTER."); } } }
Output
Enter any character : @
@ is A SPECIAL CHARACTER.