public class IdentifierTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
for(String arg : args) {
boolean start = true;
boolean validIdentifier = true;
arg.toCharArray()
// commenter pointed out my error
//for(byte b : arg.getBytes()) {
for(char b : arg.toCharArray()) {
if(start) {
validIdentifier = validIdentifier && Character.isJavaIdentifierStart(b);
start = false;
} else {
validIdentifier = validIdentifier && Character.isJavaIdentifierPart(b);
}
}
System.out.println("Identifier ""
+ arg + "" is "
+ (validIdentifier ? "" : "not ")
+ "valid");
}
}
}
Output:
>java IdentifierTest Test $ds ds$ 2$$
Identifier “Test” is valid
Identifier “$ds” is valid
Identifier “ds$” is valid
Identifier “2$$” is not valid
2 responses to “Java code to test if a string is a valid java identifier.”
great post, here is good link about Why String is immutable in Java , you might find it interesting.
This code fails for any unicode letter that don’t encode to single bytes.
To fix it, just use arg.toCharArray() and a char rather than a byte.
This should return ‘is valid’:
$ java IdentifierTest Фрэнк
Identifier “Фрэнк” is not valid