How to Check if a character is alphabet or not in Java

In this tutorial, we will learn how to Check if a Character is an alphabet or not in the Java programming language with some cool and easy examples.

Here we have some easy and efficient methods to find out.

Check if a character is an alphabet or not in Java

Here I am going to describe it in two different methods.

1. Using Predefined Method:

Easier and readable. The Character.isAlphabetic() method abstracts away the complexity and immediately provides the result.

import java.util.*;

public class AlphabetCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

  //Enter a character to take a single character as an input
        System.out.print("Enter a single character: ");
        String input = scanner.next();

        if (input.length() != 1) {
            System.out.println("Please enter exactly one character.");
        } else {
            char ch = input.charAt(0);

 // Check if the given input character is an alphabet or not 
            if (Character.isAlphabetic(ch)) {
                System.out.println(ch + " is an alphabet.");
            } else {
                System.out.println(ch + " is not an alphabet.");
            }
        }
        scanner.close();
    }
}

Output:

Enter a single character: Y
Y is an alphabet.

Explanation: The Character class isAlphabetic method in Java checks if a specified character is an alphabet.

2. Using ASCII Range: 

You could manually look at if the character belongs in the ASCII variety of lowercase letters (‘a’ to ‘z’) or uppercase letters (‘A’ to ‘Z’).

import java.util.*;

public class AlphabetCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

 //Enter a character to take a single character as an input 
        System.out.print("Enter a single character: ");
        String input = scanner.next();

        if (input.length() != 1) {
            System.out.println("Please enter exactly one character.");
        } else {
            char ch = input.charAt(0);

  // Check if the given input character is an alphabet or not
            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.");
            }
        }
        scanner.close();
    }
}

Output:

Enter a single character: n
n is an alphabet.

Explanation: This method Checks if the character belongs to the ASCII range of lowercase (a-z) or uppercase (A-Z) letters.

Leave a Reply

Your email address will not be published. Required fields are marked *