Checks if the input is a valid Java identifier - Java java.lang

Java examples for java.lang:char

Description

Checks if the input is a valid Java identifier

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String literal = "java2s.com";
        System.out.println(isValidJavaIdentifier(literal));
    }//from   ww w . j a  v a  2s . com

    /**
     * Checks if the input is a valid Java identifier
     * @param literal
     * @author Gaganis Giorgos (gaganis@users.sourceforge.net) 
     */
    private static boolean isValidJavaIdentifier(String literal) {
        boolean result = true;

        char[] literalChars = new char[literal.length()];
        literal.getChars(0, literalChars.length, literalChars, 0);

        for (int i = 0; i < literalChars.length; i++) {
            if (i == 0 && !Character.isJavaIdentifierStart(literalChars[i])) {
                result = false;
                break;
            }

            if (i != 0 && !Character.isJavaIdentifierPart(literalChars[i])) {
                result = false;
                break;
            }
        }

        return result;
    }
}

Related Tutorials