How to detect overflow when convert string to integer in java

前端 未结 3 1756
一生所求
一生所求 2021-01-12 04:02

if I want to convert a string into an int in java do you know if there is a way for me to detect overflow? by that I mean the string literal actually represents a value whic

相关标签:
3条回答
  • 2021-01-12 04:23

    You don't need to do anything.

    As the Javadoc for Integer.parseInt(str, radix) states, a NumberFormatException is thrown if the value represented by the String is not representable as an int value; i.e. if its magnitude is too big. This is described as a separate case from the case where str is badly formatted, so it is clear (to me) that this is what is meant. (And you can confirm this by reading the source code.)

    0 讨论(0)
  • 2021-01-12 04:28

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

    Yes. Catching parse exceptions would be the correct approach, but the difficulty here is that Integer.parseInt(String s) throws a NumberFormatException for any parse error, including overflow. You can verify by looking at the Java source code in the JDK's src.zip file. Luckily, there exists a constructor BigInteger(String s) that will throw identical parse exceptions, except for range limitation ones, because BigIntegers have no bounds. We can use this knowledge to trap the overflow case:

    /**
     * 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's 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;
    }
    

    If you really need to customize this for only inputs exceeding Integer.MAX_VALUE, you can do that just before throwing the custom exception, by using @Sergej's suggestion. If above is overkill and you don't need to isolate the overflow case, just suppress the exception by catching it:

    int result = 0;
    try {
        result = Integer.parseInt(s);
    } catch (NumberFormatException e) {
        // act accordingly
    }
    
    0 讨论(0)
  • 2021-01-12 04:40

    Cast String value to Long and compare Long value with 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 讨论(0)
提交回复
热议问题