2

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?

1
  • 3
    You have to use if-else for this, to check for overflow manually.. Also,you have to create your own exeption. Commented Oct 14, 2012 at 7:45

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.