java

How to check if a character is a letter in Java

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

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

So we are going to compare the given variable between ‘a’ (97) and ‘z’ (122). Same, for upper case alphabets between ‘A’ (65) and ‘Z’ (90).
 

 

How to check if a character is a letter in Java
public class Main {

    public static void main(String[] args) {

        char ch = '?';

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

Output:

? is not a letter.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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