Check if a Character Is Alphanumeric in Java

  1. Check if a Character Is Alphanumeric Using Character.isLetterOrDigit() in Java
  2. Check if a Character Is Alphanumeric by Comparing the Character in Java

This article will introduce how we can check if a character is alphanumeric in Java. A char in Java can hold alphabets, numbers as well as special symbols too. Here we will see two methods to check what the character holds.

Check if a Character Is Alphanumeric Using Character.isLetterOrDigit() in Java

In the first method, we use the isLetterOrDigit() function of the Character class. As its name suggests, isLetterOrDigit() returns the result as a boolean. isLetterOrDigit() takes a single argument that is the character to be checked.

In the example below, we have a char having the value '4'. We use Character.isLetterOrDigit() and passe this char as an argument. As we can see in the output, it returns true, which means that it is an alphanumeric value.

public class CheckCharAlpha {
    public static void main(String[] args) {
        char a = '4';

        boolean letterOrDigit = Character.isLetterOrDigit(a);
        System.out.println(letterOrDigit);
    }
}

Output:

true

Check if a Character Is Alphanumeric by Comparing the Character in Java

Another method to check if a character is alphanumeric Java involves the comparison of characters. In the below example, we have a function called isAlphaNumeric that compares the given character with lower-case, upper-case letters, and numbers. If the given character falls into one of the ranges, isAlphaNumeric() will return true otherwise false.

In the below example, we pass 'k' to isAlphaNumeric() and get true as the result, because 'k' satisfies the condition char1 >= 'a' && char1 <= 'z'.

public class CheckCharAlpha {
    public static void main(String[] args) {

        boolean letterOrDigit = isAlphaNumeric('k');
        System.out.println(letterOrDigit);
    }

    public static boolean isAlphaNumeric(char char1) {
        return (char1 >= 'a' && char1 <= 'z') || (char1 >= 'A' && char1 <= 'Z') || (char1 >= '0' && char1 <= '9');
    }
}

Output:

true

Related Article - Java Char

  • Generate Random Character in Java
  • Replace Character in String in Java
  • Related Article - Java Character

  • Iterate Over Characters of String in Java
  • Convert an ASCII Code to Char