Java Program to Check Whether a Character is Alphabet or Not

In this program, you'll learn to check whether a given character is an alphabet or not. This is done using an if else statement or a ternary operator in Java.

Example: Java Program to Check Alphabet using if else

public class Alphabet {

    public static void main(String[] args) {

        char c = '*';

        if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
            System.out.println(c + " is an alphabet.");
        else
            System.out.println(c + " is not an alphabet.");
    }
}

When you run the program, the output will be:

* is not an alphabet.

In Java, char variable stores the ASCII value of a character (number between 0 and 127) rather than the character itself.

The ASCII value of lowercase alphabets are from 97 to 122. And, the ASCII value of uppercase alphabets are from 65 to 90.

This is the reason, we compare variable c between 'a' (97) to 'z' (122). Likewise, we do the same to check for uppercase alphabets between 'A' (65) to 'Z' (90).


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

Example 2: Java Program to Check Alphabet using ternary operator

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);
    }
}

When you run the program, the output will be:

A is an alphabet.

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