English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Java other topics

Java program to check if a character is a letter

Comprehensive Java Examples

In this program, you will learn to check if a given character is a letter. This is done using if...else statements or the ternary operator in Java.

Example1: Java program to check a letter using if...else statements

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 a letter.");
        else
            System.out.println(c + " is not a letter.");
    }
}

Output Result

* Is not a letter.

In Java, a char variable stores the ASCII value of a character (0 to127between the numbers) rather than the characters themselves.

The ASCII values of lowercase letters start from97to122. The ASCII values of uppercase letters start from65to90. That is, the letter a is stored as97, the letter z is stored as122. Similarly, the letter A is stored as65, the letter Z is stored as90.

Now, when we compare the variable c between 'a' and 'z' and between 'A' and 'Z', we store the letter97to122,65to9The ASCII value of 0 is compared

Since*The ASCII value does not fall between the ASCII values of letters. Therefore, the program outputs * Is not a letter.

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

Example2: Java program to check a letter using the 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 a letter."
                : c + " is not a letter. ";
        
        System.out.println(output);
    }
}

Output Result

A is a letter.

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

Example3: Java program uses isAlphabetic() method to check letters

class Main {
  public static void main(String[] args) {
    //Declare a variable
    char c = 'a';
    //Check if c is a letter
    if (Character.isAlphabetic(c)) {
      System.out.println(c + " is a letter.");
    }
    else {
      System.out.println(c + " is not a letter.");
    }
  }
}

Output Result

a is a letter.

In the above example, please note the following expression:

Character.isAlphabetic(c)

Here, we use the isAlphabetic() method of the Character class. If the specified variable is a letter, it returns true. Therefore, the code in the if block is executed

Comprehensive Java Examples