In this java program, you'll learn how to check whether a character is an alphabet or not in java. There are various ways to check if a character is an alphabet or not. We do this using an if..else
statement or a ternary operator in Java.
//Java Program to Check Whether a Character is Alphabet or Not using if..else Statement
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
char character;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Character: ");
character = scanner.next().charAt(0);
scanner.close();
if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z')) {
System.out.print(character + " is an alphabet.");
} else {
System.out.print(character + " is not an alphabet.");
}
}
}
Enter a Character: a
a is an alphabet.
Enter a Character: 5
5 is not an alphabet.
Enter a Character: *
* is not an alphabet.
In Java, the char variable stores the ASCII value of a character (a number between 0 and 127) rather than the character itself.
The ASCII values of lowercase alphabets are from 97 to 122. And, the ASCII values of uppercase alphabets are from 65 to 90. That is, alphabet a is stored as 97 and alphabet z is stored as 122. Similarly, alphabet A is stored as 65 and alphabet Z is stored as 90.
Now, when we compare variable character
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.
//Java Program to Check Whether a Character Is an Alphabet or Not Using Ternary Operator
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
char character;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Character: ");
character = scanner.next().charAt(0);
scanner.close();
String output = (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z')
? character + " is an alphabet."
: character + " is not an alphabet.";
System.out.println(output);
}
}
Enter a Character: a
a is an alphabet.
Enter a Character: 1
1 is not an alphabet.
Enter a Character: $
$ is not an alphabet.
In this java program, we have used the isAlphabetic()
method of the Character
class. This method returns true
if the specified variable is an alphabet. Hence, the code inside the if
block is executed.
//Java Program to Check Alphabet using isAlphabetic() Method
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
char character;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Character: ");
character = scanner.next().charAt(0);
scanner.close();
// checks if character is an alphabet
if (Character.isAlphabetic(character)) {
System.out.println(character + " is an alphabet.");
}
else {
System.out.println(character + " is not an alphabet.");
}
}
}
Enter a Character: a
a is an alphabet.
Enter a Character: 7
7 is not an alphabet.
Enter a Character: @
@ is not an alphabet.
Comments