Reputation: 35404
Let's have a simple code as below
public class Sandbox {
public static void run(String[] args) {
int i = Integer.MAX_VALUE;
int j = i+1;
System.out.println(i);
System.out.println(j);
}
}
This will print output
2147483647
-2147483648
Value at j is overlowed without any notice to me when the code is executed.
I use Netbeans IDE to run this code.
Is it possible to configure the system to notify us when such arithmetic overflow occurs?
Upvotes: 2
Views: 1198
Reputation: 78
In the Math API since Java 8, you can use:
Math.addExact(i, 1);
It will throw an ArithmeticException
if the result overflows an int
.
Upvotes: 1
Reputation: 16403
See the last sentence in the Java Language Specification (Chapter 15.18.2. Additive Operators (+ and -) for Numeric Types) :
Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a runtime exception.
For a lengthy article on this problem and the presentation of a tool for workaround see the article Signalling Integer Overflows in Java.
Upvotes: 4