W3docs

Determine if a String is an Integer in Java

To determine if a string is an integer in Java, you can use the isDigit() method of the Character class to check if each character in the string is a digit. Here's an example:

To determine if a string is an integer in Java, you can use several approaches. The first method checks each character using Character.isDigit(), while others rely on Integer.parseInt() or regular expressions. Here's an example of the character-checking approach:


public static boolean isInteger(String s) {
    if (s == null || s.isEmpty()) {
        return false;
    }
    int start = (s.charAt(0) == '-') ? 1 : 0;
    for (int i = start; i < s.length(); i++) {
        if (!Character.isDigit(s.charAt(i))) {
            return false;
        }
    }
    return true;
}

This method iterates through each character and verifies it is a digit. It returns false for null, empty strings, or any non-digit characters. It now correctly handles both positive and negative integers.

You can also use the parseInt() method of the Integer class to check if a string can be parsed as an integer. It throws a NumberFormatException if the string is not a valid integer, so you can wrap it in a try-catch block. Add a null/empty check to prevent exceptions:


public static boolean isInteger(String s) {
    if (s == null || s.isEmpty()) {
        return false;
    }
    try {
        Integer.parseInt(s);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

This method returns true if the string represents a valid integer within the int range, and false otherwise. Note that Integer.parseInt() expects exact formatting and does not accept leading or trailing whitespace.

Note that Integer.parseInt() throws an exception for strings outside the Integer.MIN_VALUE to Integer.MAX_VALUE range. A regular expression can validate the format, but it does not check the numeric range. Here's an example:


public static boolean isInteger(String s) {
    if (s == null || s.isEmpty()) {
        return false;
    }
    return s.matches("^-?\\d+$");
}

This regular expression matches strings with an optional negative sign followed by one or more digits. Remember that it only validates the format and will still require range checking if you parse the result.