DEV Community

Yousuf Ibrahim Gani
Yousuf Ibrahim Gani

Posted on

What happens when you add 1 to Integer.MAX_VALUE in Java?

Integer.MAX_VALUE + 1;

Does it throw an exception? Like a Numeric overflow exception

This is pretty interesting when I first got to know about it.

The answer is it doesn’t throw any exception, compile time or runtime.

It gives you an answer and that will be Integer.MIN_VALUE

Integer.MAX_VALUE + 1 = Integer.MIN_VALUE;

Yes, you read it right. This happens because of the reason that Java represents the numbers in binary format and uses a Two’s complement representation while doing any operations on the number like addition, subtraction etc.

In Two’s complement form, the leftmost digit in binary indicates the sign, 0 is positive and 1 is Negative

Integer.MAX_VALUE = 2147483647 = 01111111111111111111111111111111

 Integer.MIN_VALUE = -2147483648 = 10000000000000000000000000000000

So when you add

01111111111111111111111111111111 + 00000000000000000000000000000001 = 10000000000000000000000000000000

Learn more about it here: https://lnkd.in/ga8Q29u9

This is school mathematics that we usually never give any importance to, but this is one of the concepts that is responsible for thousands of software running successfully, which are the engines for many successful organizations.

Next time when you use Integers in Java and perform any operation, you will know what happens under the hood.

java #software #mathematics #concepts #learnings

Top comments (2)

Collapse
 
incrementis profile image
Akin C.

Hello Yousuf Ibrahim Gan,

Thanks for your article.
It's a good read and a reminder of programming basics.

When I read this, it reminded me of the story about Ariane 5.
An integer overflow caused the satellite to self-destruct.

Nice that you are here on Dev.to.

Collapse
 
yousufibrahim28 profile image
Yousuf Ibrahim Gani

An Integer overflow caused satellite destruction woah! Will google it.

Thanks for the appreciation Akin C! It is nice that you liked it.