import java.util.Scanner;
public class AlphabetChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = input.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.");
}
}
}
Enter a character: R
R is an alphabet.
Scanner
class. Then, we use an if
statement to check whether the character is an alphabet or not.ASCII value
of the character is within the range of ASCII values
for uppercase and lowercase letters. If it is, we print a message indicating that the character is an alphabet. Otherwise, we print a message indicating that the character is not an alphabet.System.out.println()
to print the appropriate message to the console.public class Alphabet {
public static void main(String[] args) {
char c = 'A';
String output = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
? c + " is an alphabet."
: c + " is not an alphabet.";
System.out.println(output);
}
}
A is an alphabet.​
if else
statement is replaced with ternary operator (? :)
.isAlphabetic()
Method :class Main {
public static void main(String[] args) {
// declare a variable
char c = 'a';
// checks if c is an alphabet
if (Character.isAlphabetic(c)) {
System.out.println(c + " is an alphabet.");
}
else {
System.out.println(c + " is not an alphabet.");
}
}
}
a is an alphabet.
In the above example, notice the expression,
Character.isAlphabetic(c)
Here, we have used the isAlphabetic()
method of the Character
class. It returns true
if the specified variable is an alphabet. Hence, the code inside if
block is executed.