Determine if a String is a legal Java Identifier

Java 8Object Oriented ProgrammingProgramming

To determine if a String is a legal Java Identifier, use the Character.isJavaIdentifierPart() and Character.isJavaIdentifierStart() methods.

Character.isJavaIdentifierPart()

The java.lang.Character.isJavaIdentifierPart() determines if the character (Unicode code point) may be part of a Java identifier as other than the first character.

A character may be part of a Java identifier if any of the following are true.

  • it is a letter
  • it is a currency symbol (such as '$')
  • it is a connecting punctuation character (such as '_')
  • it is a digit
  • it is a numeric letter (such as a Roman numeral character)

Character.isJavaIdentifierStart()

The java.lang.Character.isJavaIdentifierStart() determines if the character (Unicode code point) is permissible as the first character in a Java identifier.

A character may start a Java identifier if and only if one of the following conditions is true.

  • isLetter(ch) returns true
  • getType(ch) returns LETTER_NUMBER
  • the referenced character is a currency symbol (such as '$')
  • the referenced character is a connecting punctuation character (such as '_').

The following is an example that checks for individual characters in a string as well as an entire string. It checks whether the string can be a legal Java Identifier or not.

Example

Live Demo

import java.util.*;
public class Demo {
   public static void main(String []args) {
      char ch1, ch2;
      ch1 = 's';
      ch2 = '_';
      String str = "jkv_yu";
      System.out.println("Checking characters for valid identifier status...");
      boolean bool1, bool2;
      bool1 = Character.isJavaIdentifierPart(ch1);
      bool2 = Character.isJavaIdentifierStart(ch2);
      String str1 = ch1 + " may be a part of Java identifier = " + bool2;
      String str2 = ch2 + " may start a Java identifier = " + bool2;
      System.out.println(str1);
      System.out.println(str2);
      System.out.println("\nChecking an entire string for valid identifier status...");
      System.out.println("The string to be checked: "+str);
      if (str.length() == 0 || !Character.isJavaIdentifierStart(str.charAt(0))) {
         System.out.println("Not a valid Java Identifier");
      }
      for (int i = 1; i < str.length(); i++) {
         if (!Character.isJavaIdentifierPart(str.charAt(i))) {
            System.out.println("Not a valid Java Identifier");
         }
      }
      System.out.println("Valid Java Identifier");
   }
}

Output

Checking characters for valid identifier status...
s may be a part of Java identifier = true
_ may start a Java identifier = true

Checking an entire string for valid identifier status...
The string to be checked: jkv_yu
Valid Java Identifier
raja
Published on 13-Nov-2018 10:34:13
Advertisements