Handle Non-Letter Characters
In the previous steps, we've seen how Character.isLetter()
works with both uppercase and lowercase letters. Now, let's explicitly test how it handles various non-letter characters, such as digits, symbols, and whitespace.
-
Open the LetterCheck.java
file in the WebIDE editor. It should be in the ~/project
directory.
-
Modify the main
method to include more examples of non-letter characters. Replace the existing main
method content with the following:
public static void main(String[] args) {
char digit0 = '0';
char symbolDollar = '$';
char space = ' ';
char newLine = '\n'; // Newline character
char comma = ',';
char upperCaseA = 'A'; // Keep a letter for comparison
boolean isDigit0Letter = Character.isLetter(digit0);
boolean isSymbolDollarLetter = Character.isLetter(symbolDollar);
boolean isSpaceLetter = Character.isLetter(space);
boolean isNewLineLetter = Character.isLetter(newLine);
boolean isCommaLetter = Character.isLetter(comma);
boolean isUpperCaseALetter = Character.isLetter(upperCaseA);
System.out.println("Is '" + digit0 + "' a letter? " + isDigit0Letter);
System.out.println("Is '" + symbolDollar + "' a letter? " + isSymbolDollarLetter);
System.out.println("Is space a letter? " + isSpaceLetter); // Print "space" instead of the character itself for clarity
System.out.println("Is newline a letter? " + isNewLineLetter); // Print "newline"
System.out.println("Is '" + comma + "' a letter? " + isCommaLetter);
System.out.println("Is '" + upperCaseA + "' a letter? " + isUpperCaseALetter);
}
We've added examples for a digit, a symbol, a space, a newline character, and a comma. We also kept an uppercase letter for comparison. Notice how we print "space" and "newline" for clarity, as printing the characters themselves might not be visible or clear in the output.
-
Save the modified LetterCheck.java
file (Ctrl + S
or Cmd + S
).
-
Open the Terminal and ensure you are in the ~/project
directory.
-
Compile the updated Java file:
javac LetterCheck.java
If the compilation is successful, you will see no output.
-
Run the compiled program:
java LetterCheck
You should see output similar to this:
Is '0' a letter? false
Is '$' a letter? false
Is space a letter? false
Is newline a letter? false
Is ',' a letter? false
Is 'A' a letter? true
This output demonstrates that Character.isLetter()
correctly identifies digits, symbols, spaces, and newline characters as non-letters. This confirms that the method is specifically designed to check for characters that are part of an alphabet.
You have now successfully used Character.isLetter()
to check various types of characters, including uppercase letters, lowercase letters, digits, symbols, and whitespace. This method is useful when you need to process text and identify or filter out letter characters.