How do I check if a character representing an alphabet?

In the previous example you’ve learned how to use the Character.isDigit() method to check if a character representing a digit.

In this example you will learn how to check if a character representing a letter. You can use the Character.isLetter(char c) method to check if a character is a valid letter. This method will return a true value for a valid letter characters and false if the character is not a valid letter.

In the code snippet below you will also learn how to use the toCharArray() method to covert a string into an array of char. Here we use the method so that we can check every character in the for-each loop to see is the character is a letter or not.

package org.kodejava.lang;

public class CharacterIsLetterExample {
    public static void main(String[] args) {
        String name = "Kode Java 123";

        // Determines if the specified character is a letter
        if (Character.isLetter(name.charAt(5))) {
            System.out.println("The fifth character (" +
                    name.charAt(5) + ") is an alphabet!");
        }

        // Iterates all characters in the string to see if it is
        // a letter or not.
        for (char c : name.toCharArray()) {
            if (Character.isLetter(c)) {
                System.out.println(c + " is a letter.");
            } else {
                System.out.println(c + " not a letter.");
            }
        }
    }
}

The code will print the following output:

The fifth character (J) is an alphabet!
K is a letter.
o is a letter.
d is a letter.
e is a letter.
  not a letter.
J is a letter.
a is a letter.
v is a letter.
a is a letter.
  not a letter.
1 not a letter.
2 not a letter.
3 not a letter.
Wayan

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.