Search code examples
javaintegernumberformatexception

How to check an integer isn't bigger than MAX_VALUE when bing parsed with Integer.parseInt()


I am writing a Java program that takes a number from a user and performs calculations on it. I am taking the input with BefferedReader and I cannot use Scanner. The input string is parsed to an int value.

How can I check that the input string is not bigger than Integer.MAX_VALUE?

It throws a NumberFormatException and I could handle this but that would also throw for any non-numberic input that would be handled differently.

default:
    input.push(Integer.valueOf(input_string));
    break;

Solution

  • One way would be to parse the value as a BigInteger and then use intValueExact() to turn it into an int:

    int i = new BigInteger(inputString).intValueExact();
    

    This throws NumberFormatException if the value is non-numeric, or ArithmeticException if the value is too big or small to store in an int.