English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Determine if a string is a valid Java identifier

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

Character.isJavaIdentifierPart()

java.lang.Character.isJavaIdentifierPart() determines whether the character (Unicode code point) can be part of a Java identifier, not the first character.

If any of the following conditions are met, the character may be part of a Java identifier.

  • It is a letter

  • It is a currency symbol (e.g., "$")

  • It is a connected punctuation symbol (e.g., '_')

  • It is a numeral

  • It is a numeral-letter (e.g., Roman numeral characters)

Character.isJavaIdentifierStart()

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

and only when one of the following conditions is true, the character can start a Java identifier.

  • isLetter(ch) returns true

  • getType(ch) returns LETTER_NUMBER

  • The referenced character is a currency symbol (e.g., "$").

  • The referenced character is a connected punctuation character (e.g., "_").

This is an example of checking a single character within a string and the entire string. It checks if the string can be a valid Java identifier.

Example

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 Result

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