Google News
logo
Java Program to Check Whether a Character is Alphabet or Not
In the following example Java program to check whether a character is an alphabet or not :
Program :
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.");
        }
    }
}
Output :
Enter a character: R
R is an alphabet.
In this program, we first ask the user to input a character using the Scanner class. Then, we use an if statement to check whether the character is an alphabet or not.

We do this by checking whether the 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.

We use System.out.println() to print the appropriate message to the console.


You can also solve the problem using ternary operator in Java.

Java Program to Check Alphabet using ternary operator :

Program :
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);
    }
}
Output :
A is an alphabet.​

In the above program, the if else statement is replaced with ternary operator (? :).

Another Example: Java Program to Check Alphabet using 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.");
    }
  }
}

Output :

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.