Java isJavaLetterOrDigit() Example

Many methods exist in java.lang.Character class used for different purposes. Some methods are useful for checking the character is a digit or letter or is a uppercase letter or lowercase etc. At the sametime, some methods can modify the case of the letters from uppercase to lowercase or vice versa.

Few more methods exist whether the character is fit to be the first character in a Java identifier like isJavaIdentifierStart(). Another method exist, isJavaLetterOrDigit() to know whether character can fit anywhere in the Java identifier. We know a Java identifier should start with a letter, a digit or an underscore. Except the first character, the remaining characters can be a combination of digits, letters, $ symbol, underscore etc., but not special characters and spaces. isJavaLetterOrDigit(char ch) returns true for all fitting characters and returns false for special characters and spaces.

Note: isJavaLetterOrDigit(char ch) is very different from isLetterOrDigit(char ch).

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

  • public static boolean isJavaLetterOrDigit(char ch): Checks the specified character ch is permitted to present anywhere in the Java identifier. Returns a boolean value of true if suits, else false. This method is deprecated in favor of isJavaIdentifierPart(char).
Following Java isJavaLetterOrDigit() 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.isJavaLetterOrDigit(ch1);
   boolean b2 = Character.isJavaLetterOrDigit(ch2);

   System.out.println(ch1 + " is permitted in Java identifier: " + b1);     
   System.out.println(ch2 + " is permitted in Java identifier: " + b2);     
   System.out.println("_ is permitted in Java identifier: " + Character.isJavaLetterOrDigit('_'));
   System.out.println("5  is permitted in Java identifier: " + Character.isJavaLetterOrDigit('5'));
   System.out.println("+ is permitted in Java identifier: " + Character.isJavaLetterOrDigit('+'));

Java isJavaLetterOrDigit() Example
Output screenshot on Java isJavaLetterOrDigit() Example

Observe the special characters * and + returned false.

Observe the screenshot, the compiler raised deprecation warning with isJavaLetterOrDigit(char) which is replaced in favor of isJavaIdentifierPart(char).

Leave a Comment

Your email address will not be published.