如何在Java中将String转换为int,同时注意int的下溢和上溢



我正在使用以下代码将String转换为int:

int foo = Integer.parseInt("1234");
How can I make sure int value does not overflow or underflow?

As the documentation says, if the input string does not contain a parseable integer, a NumberFormatException will be thrown. That includes inputs that are integers but are outside of the range of an int.

The terms "underflow" and "overflow" aren't quite the terms you're looking for here: they refer to situations where you have a couple of integers in the valid range (say, 2 billion) and you add them together (or perform some arithmetic operation that achieves a similar effect) and get an integer outside of the valid range. This usually results in problems like wrapping into the negatives because of Two's Complement and such. Your question, on the other hand, is just a simple case of string-encoded integers lying outside of the valid range.

You can always check:

long pre_foo = Long.parseLong("1234");
if (pre_foo < Integer.MIN_VALUE || pre_foo > Integer.MAX_VALUE){
    //Handle this situation, maybe keep it a long, 
    //or use modula to fit it in an integer format
}
else {
    int foo = (int) pre_foo;
}

最新更新