How to detect overflow when converting string to integer in java

if I want to convert a string to int in java Do you know if there is a way to detect overflow? by this I mean that the string literal actually represents a value that is greater than MAX_INT?

java doc did not mention this. he simply says that if the string cannot be parsed as an integer, it will not mention a word about overflow through FormatException.

+5
source share
3 answers

If I want to convert a string to int in java, do you know if there is a way to detect overflow?

. , , Integer.parseInt(String s) NumberFormatException , . , Java JDK src.zip. , BigInteger(String s), , , BigInteger . , :

/**
 * Provides the same functionality as Integer.parseInt(String s), but throws
 * a custom exception for out-of-range inputs.
 */
int parseIntWithOverflow(String s) throws Exception {
    int result = 0;
    try {
        result = Integer.parseInt(s);
    } catch (Exception e) {
        try {
            new BigInteger(s);
        } catch (Exception e1) {
            throw e; // re-throw, this was a formatting problem
        }
        // We're here iff s represents a valid integer that outside
        // of java.lang.Integer range. Consider using custom exception type.
        throw new NumberFormatException("Input is outside of Integer range!");
    }
    // the input parsed no problem
    return result;
}

, Integer.MAX_VALUE, , , @Sergej. , , , :

int result = 0;
try {
    result = Integer.parseInt(s);
} catch (NumberFormatException e) {
    // act accordingly
}
+8

String Long Integer.Max_value

    String bigStrVal="3147483647";        
    Long val=Long.parseLong(bigStrVal);
    if (val>Integer.MAX_VALUE){
        System.out.println("String value > Integer.Max_Value");
    }else
        System.out.println("String value < Integer.Max_Value");
0

.

As pointed out by Javadoc for Integer.parseInt(str, radix), is generated NumberFormatExceptionif the value represented by String is not represented as a intvalue; those. if its value is too large. This is described as a separate case from the case when it is strpoorly formatted, so it is clear (to me) that this is what is meant. (And you can confirm this by reading the source code.)

0
source

All Articles