Take the 2-minute tour ×

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;

This will print output



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?

share|improve this question
You have to use if-else for this, to check for overflow manually.. Also,you have to create your own exeption. –  Rohit Jain Oct 14 '12 at 7:45
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
add comment

As Rohit Jain mentioned, you have to check it manually, something like this:

if ( j < Integer.MIN_VALUE ||  j> Integer.MAX_VALUE ) 
 throw new RuntimeException("Underflow/Overflow occured");

However , if the fluctuation becomes so high that the result comes back in the range, it will not be caught.

share|improve this answer
add comment

Your Answer


