জাভা কীওয়ার্ড (যেমন class, int, if ইত্যাদি) রিজার্ভড, সেগুলো আইডেন্টিফায়ার হিসেবে ব্যবহার করা যায় না। স্ট্রিংটি জাভা কীওয়ার্ড কিনা চেক করতে Character.isJavaIdentifierStart() এবং Character.isJavaIdentifierPart() ব্যবহার করা যায়, কিন্তু রিজার্ভড ওয়ার্ড লিস্ট আলাদা রাখতে হয়।
কাস্টম ভ্যালিডেশন উদাহরণ
import java.util.*;
public class KeywordCheck {
// জাভা কীওয়ার্ড সেট (আংশিক)
private static final Set JAVA_KEYWORDS = Set.of(
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char",
"class", "const", "continue", "default", "do", "double", "else", "enum",
"extends", "final", "finally", "float", "for", "goto", "if", "implements",
"import", "instanceof", "int", "interface", "long", "native", "new", "package",
"private", "protected", "public", "return", "short", "static", "strictfp",
"super", "switch", "synchronized", "this", "throw", "throws", "transient",
"try", "void", "volatile", "while", "_", "true", "false", "null"
);
public static boolean isValidIdentifier(String str) {
if (str == null || str.isEmpty()) return false;
if (JAVA_KEYWORDS.contains(str)) return false; // কীওয়ার্ড হলে অবৈধ
if (!Character.isJavaIdentifierStart(str.codePointAt(0))) return false;
for (int i = 1; i < str.length(); i++) {
if (!Character.isJavaIdentifierPart(str.codePointAt(i))) return false;
}
return true;
}
public static void main(String[] args) {
String[] tests = {"Hello", "class", "123abc", "_var", "$value", "for"};
for (String t : tests) {
System.out.println(t + " -> " + (isValidIdentifier(t) ? "Valid" : "Invalid (Keyword/Illegal)"));
}
}
}
আউটপুট
Hello -> Valid class -> Invalid (Keyword/Illegal) 123abc -> Invalid (Keyword/Illegal) _var -> Valid $value -> Valid for -> Invalid (Keyword/Illegal)