Search code examples
javaparseint

parseInt vs isDigit


I need my code to return true if the parameter is the String representation of an integer between 0 and 255 (including 0 and 255), false otherwise.

For example: Strings "0", "1", "2" .... "254", "255" are valid.

Padded Strings (such as "00000000153") are also valid.

isDigit apparently would also work but i was wondering if this would be more beneficial and/or this would even work with Padded Strings?

public static boolean isValidElement(String token) {
    int foo = Integer.parseInt("token");
    if(foo >= 0 && foo <= 255)
        return true;
    else 
        return false;
    }

Solution

  • isDigit would not work, because it takes a character as input, and returns true if it is a digit from 0 to 9. [Reference : isDigit javadoc]

    Since in your case you need to test string representations of all numbers from 0 to 255 hence you must use parseInt.

    Additionally also check if the token passed is a valid number by catching NumberFormatException and returning false in case it is not a valid integer.

    public static boolean isValidElement(String token) {
        try{
            int foo = Integer.parseInt(token);
            if(foo >= 0 && foo <= 255)
                return true;
            else 
                return false;
        } catch (NumberFormatException ex) {
            return false;
        }
    }