Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
character
alphanumeric
if else
communitycreator

How to check if a character is alphanumeric in Java with if-else

okwudili onyejiaku

Overview

Without any inbuilt method, we can check if a given character is alphanumeric or not. An alphanumeric character is a character that is either a number or an alphabet. The logic to find out if a character is alphanumeric is listed below:

  • Is the character greater than or equal to '0' and less than or equal to 9?
  • Or is the character greater than or equal to a and less than or equal to z?
  • Or is the character greater than or equal to A and less than or equal to Z?

We can see if a character is an alphanumeric character with these given conditions above.

Syntax

if ((character >= '0' && character <= '9') || (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z')){
    // character is alphanumeric
}else{
    // character is not alphanumeric
}
Syntax to check if a character is alphanumeric in Java without an inbuilt method

Parameters

character: This is the character we want to check if it is alphanumeric or not.

Example

class HelloWorld {
    // create function to check if alphanumeric
    static void checkIfAlphanumeric(char character){
      if ((character >= '0' & character <= '9') || (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z')){
        System.out.println(character +" is alphanumeric");
      }else{
        System.out.println(character +" is not alphanumeric");
      }
    }
    public static void main( String args[] ) {
        // check if some characters are alphanumeric
        checkIfAlphanumeric('e');
        checkIfAlphanumeric('1');
        checkIfAlphanumeric('r');
        checkIfAlphanumeric('%');
        checkIfAlphanumeric(',');
    }
}
Check if a character is alphanumeric in Java

Explanation

  • Line 3: We create a function to check if a character is alphanumeric. It takes a character as a parameter and applies the condition discussed above.
  • Lines 12–16: We check if some characters are alphanumeric with the function we created.

RELATED TAGS

java
character
alphanumeric
if else
communitycreator
RELATED COURSES

View all Courses

Keep Exploring