Search code examples
javaregexkeywordreserved-words

Get a list of all Java reserved Keywords


I'm looking for a way to retrieve all the saved keywords in Java into some kind of data structure. For example: "for, while, if, else, int, double, etc."

I need to do a name validation on a string, to be specific, I need to make sure it does not equal to any java keywords.

Is there a specific way of retrieving all the keywords into one data structure? or do I need to just build a regex string with all these keywords in it : "for|while|if|..." and try and match my string against it?

Thanks


Solution

  • From axis.apache.org

    Basically, Pre-Sort the keywords and store it in an array and using Arrays.binarySearch on your keyword for the good'ol O(logn) complexity

    import java.util.Arrays;
    
        public class MainDemo {
            static final String keywords[] = { "abstract", "assert", "boolean",
                    "break", "byte", "case", "catch", "char", "class", "const",
                    "continue", "default", "do", "double", "else", "extends", "false",
                    "final", "finally", "float", "for", "goto", "if", "implements",
                    "import", "instanceof", "int", "interface", "long", "native",
                    "new", "null", "package", "private", "protected", "public",
                    "return", "short", "static", "strictfp", "super", "switch",
                    "synchronized", "this", "throw", "throws", "transient", "true",
                    "try", "void", "volatile", "while" };
    
            public static boolean isJavaKeyword(String keyword) {
                return (Arrays.binarySearch(keywords, keyword) >= 0);
            }
    
            //Main method
            public static void main(String[] args) {
                System.out.println(isJavaKeyword("void"));
    
            }
    
        }
    

    Output:

    True


    Alternatively, as users @typeracer,@holger suggested in the comments, you can use SourceVersion.isKeyword("void") which uses javax.lang.model.SourceVersion library and Hashset Data structure internally and keeps the list updated for you.