10

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 which is larger than MAX_INT?

java doc didn't mention it.. it just says that if the string can not be parsed as an integer, it will through FormatException didn't mention a word about overflow..

yangsuli
  • 1,252
  • 5
  • 16
  • 33
  • http://stackoverflow.com/questions/8030485/java-integer-parseint-failed-to-parse-a-string – Andrey Starodubtsev Feb 26 '12 at 06:32
  • @darkmist Thanks. Knowing it throws an exception helps. I still what to know what kind of exception and such...Could you point me to the documentation which describes the behavior? – yangsuli Feb 26 '12 at 06:35
  • `NumberFormatException` ( `parseInt` declared as `public static int parseInt(String s, int radix) throws NumberFormatException` ). BTW, there's a sample in http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html for too long number that doesn't fit in `int`. – Andrey Starodubtsev Feb 26 '12 at 06:38
  • @darkmist An exception of type NumberFormatException is thrown if any of the following situations occurs: (doesnt include too large value...) The first argument is null or is a string of length zero. The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX. Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1. The value represented by the string is not a value of type int. – yangsuli Feb 26 '12 at 06:47
  • @darkmist Also how about String.intValue's behavior? – yangsuli Feb 26 '12 at 06:47
  • if you need to distinguish 'too long to fit in int type' situation from other causes of NumberFormatException, you can write your own conversion procedure or verify incoming number and radix for conditions you mentioned. – Andrey Starodubtsev Feb 26 '12 at 06:59

3 Answers3

13

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
}
calebds
  • 25,670
  • 9
  • 46
  • 74
  • Catching and throwing `Exception` is Bad Practice. – Stephen C Feb 26 '12 at 08:17
  • @Stephen that sounds interesting. Any explanation or reference? – calebds Feb 26 '12 at 16:50
  • @paislee Thanks. I guess I only want to ask does NFE detect overflow, as java doc didn't mention it. But knowing how to isolate the case helps too. However it's surprising to me that the source code (not some kind of standard) is the final resort for information... – yangsuli Feb 26 '12 at 18:28
1

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");
Sergej Raishin
  • 535
  • 4
  • 7
  • 1
    @yangsuli Wrap it in a function and you won't have to look at it again. IMHO this is pretty elegant.. except Long has a MAX_VALUE as well, so its still not guaranteed to parse. – calebds Feb 26 '12 at 07:03
  • @paislee Long.Max_Value exactly why it is a non-solution...Catch an exception seems much more elegant to me here (of course, if Java allows me to do so...) – yangsuli Feb 26 '12 at 07:07
  • I'm afraid that this is worse than nothing as it gives the impression of doing the job but does not because numbers that overflow a long are not handled. – Keith Whittingham Jul 07 '16 at 06:21
0

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.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • It may be _described_ as a separate case, but in practice there is no immediate way to differentiate the cases. The method throws exceptions in 6 cases, and they are all identical exceptions. See `src` code. – calebds Feb 26 '12 at 07:44
  • But the OP asked about *detecting* overflow, not *distinguishing* it from other problems. The NFE *does* detect overflow, and I think that is what was really concerning the OP. – Stephen C Feb 26 '12 at 08:10