Java Character isJavaLetter() Example

Java Character API comes with many methods to test whether a character is a digit or letter or defined in Unicode or can suit to be a part of Java identifier etc. This type of testing is useful in situations when a Java program can accept a character or not.

Following is the method signature as defined in java.lang.Character class.

  • public static boolean isJavaLetter(char ch): Checks the specified character ch is permitted as the first character in a Java identifier. Returns a boolean value of true if suits, else false. This method is deprecated in favor of isJavaIdentifierStart(char).

We know earlier in Java Rules of Identifiers, an identifier in Java should start with

a) a letter OR
b) an underscore OR
c) a $ symbol

For example, 5mangoesCost will not be permitted as Java identifier as the identifier starts with a digit. To check the given character is a letter or underscore or $ symbol, a method is given in Character class isJavaLetter(char ch). The method returns true if specified character ch is either a letter or underscore or $. For anyone other than these three, the method returns false.

Following example illustrates. Just for interest, special characters are also checked.

public class CharacterFunctionDemo
{
  public static void main(String args[])
  {
   char ch1 = 'a';
   char ch2 = '$';                      

   boolean b1 = Character.isJavaLetter(ch1);
   boolean b2 = Character.isJavaLetter(ch2);

   System.out.println("ch1 + " is permitted as first letter in Java identifier: " + b1);     
   System.out.println(ch2 + " is permitted as first letter in Java identifier: " + b2);     
   System.out.println("_ is permitted as first letter in Java identifier: " + Character.isJavaLetter('_'));

   System.out.println("\n5  is permitted as first letter in Java identifier: " + Character.isJavaLetter('5'));
   System.out.println("* is permitted as first letter in Java identifier: " + Character.isJavaLetter('*'));
  }
}

Java Character isJavaLetter() Example

Other than letter, $ and underscore, all letters displayed false.

Observe the compilation warning message in the screenshot. isJavaLetter(char) is deprecated in favour of isJavaIdentifierStart(char).

Leave a Comment

Your email address will not be published.