Thursday 12 July 2018

How to check whether given character is part of Java identifier variable name or not?

'java.lang.Character' class provides 'isJavaIdentifierPart' method to check whether given character is part of a valid java identifier (other than first character of the identifier name) or not.

A character can be part of java identifier, if any of the following conditions are true.

a.   it is a letter
b.   it is a currency symbol (such as '$')
c.   it is a connecting punctuation character (such as '_')
d.   it is a digit
e.   it is a numeric letter (such as a Roman numeral character)
f.    it is a combining mark
g.   it is a non-spacing mark
h.   isIdentifierIgnorable returns true for the character

'isJavaIdentifierPart' method is available in below overloaded forms.

public static boolean isJavaIdentifierPart(char ch)
public static boolean isJavaIdentifierPart(int codePoint)
First version of the 'isJavaIdentifierPart' method do not support supplementary characters. Characters whose code points are greater than U+FFFF are called supplementary characters.


Find the below working application.

Test.java

package com.sample.app;

public class Test {

 public static void main(String args[]) {

  System.out.println("Is '@' valid identifier ?" + Character.isJavaIdentifierPart('@'));
  System.out.println("Is '_' valid identifier ?" + Character.isJavaIdentifierPart('_'));
  System.out.println("Is '9' valid identifier ?" + Character.isJavaIdentifierPart('9'));

 }
}

Output

Is '@' valid identifier ?false
Is '_' valid identifier ?true
Is '9' valid identifier ?true

Note:
If you want to check whether an identifier can start with given character or not by using below methods provided by 'java.lang.Character' class.

public static boolean isJavaIdentifierStart(char ch)
public static boolean isJavaIdentifierStart(int codePoint)

You may like



No comments:

Post a Comment