How does Java handle integer underflows and overflows?
Leading on from that, how would you check/test that this is occurring?
How does Java handle integer underflows and overflows?
Leading on from that, how would you check/test that this is occurring?
I think you should use something like this and it is called Upcasting:
You can read further here: Detect or prevent integer overflow
It is quite reliable source.
There is one case, that is not mentioned above:
will produce:
This case was discussed here: Integer overflow produces Zero.
It wraps around.
e.g:
prints
By default, Java's int and long math silently wrap around on overflow and underflow. (Integer operations on other integer types are performed by first promoting the operands to int or long, per JLS 4.2.2.)
As of Java 8,
java.lang.Math
providesaddExact
,subtractExact
,multiplyExact
,incrementExact
,decrementExact
andnegateExact
static methods for both int and long arguments that perform the named operation, throwing ArithmeticException on overflow. (There's no divideExact method -- you'll have to check the one special case (MIN_VALUE / -1
) yourself.)As of Java 8, java.lang.Math also provides
toIntExact
to cast a long to an int, throwing ArithmeticException if the long's value does not fit in an int. This can be useful for e.g. computing the sum of ints using unchecked long math, then usingtoIntExact
to cast to int at the end (but be careful not to let your sum overflow).If you're still using an older version of Java, Google Guava provides IntMath and LongMath static methods for checked addition, subtraction, multiplication and exponentiation (throwing on overflow). These classes also provide methods to compute factorials and binomial coefficients that return
MAX_VALUE
on overflow (which is less convenient to check). Guava's primitive utility classes,SignedBytes
,UnsignedBytes
,Shorts
andInts
, providecheckedCast
methods for narrowing larger types (throwing IllegalArgumentException on under/overflow, not ArithmeticException), as well assaturatingCast
methods that returnMIN_VALUE
orMAX_VALUE
on overflow.It doesn't do anything -- the under/overflow just happens.
A "-1" that is the result of a computation that overflowed is no different from the "-1" that resulted from any other information. So you can't tell via some status or by inspecting just a value whether it's overflowed.
But you can be smart about your computations in order to avoid overflow, if it matters, or at least know when it will happen. What's your situation?