How does Java handle integer underflows and overflows?
Leading on from that, how would you check/test that this is occurring?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.
You can make use of the
Math#addExact()andMath#subtractExact()methods which will throw anArithmeticExceptionon overflow.You can substitute
intbylongto perform the same checks forlong.The source code can be found here and here respectively.
Of course, you could also just use them right away instead of hiding them in a
booleanutility method.If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g.
longor maybejava.math.BigInteger. The last one doesn’t overflow, practically, the available JVM memory is the limit.