Increase MAX_VALUE of type primitve
I am trying to understand the following code:
int i = Integer.MAX_VALUE;
double d = Double.MAX_VALUE;
System.out.println(i + ":" + (i+1));
System.out.println(d + ":" + (d+1));
Output:
2147483647:-2147483648 1.7976931348623157E308:1.7976931348623157E308
For the first line, it i
is equal to the maximum integer value, and incrementing it results in the smallest integer value. Why doesn't the same thing happen with d
?
Is there a simple explanation for this behavior?
source to share
The integer overflows because it is in two complement format .
-
Integer.MAX_VALUE
presented0111...111
-
Integer.MIN_VALUE
presented1000...000
So when you try to add 1 to Integer.MAX_VALUE
, according to the usual adding rules, you get Integer.MIN_VALUE
. This is called overflow.
Floating point numbers have a different representation that defies this type of overflow. They are all approximations, and the closest approximation to the value you gave it is Double.MAX_VALUE
.
source to share
On double overflow, its value becomes Infinity
, not a negative number.
The reason you cannot overflow by simply adding 1 in Double.MAX_VALUE
is MAX_VALUE + 1 == MAX_VALUE
because the precision of the doublings is not enough to make the difference between the two numbers.
You can actually add quite a large amount before moving on to the next available twin. For example, this doesn't overflow either:
System.out.println(Double.MAX_VALUE + 1e100); //still Double.MAX_VALUE
This overflows as expected:
System.out.println(m + (Math.ulp(m) / 2)); //Infinity
source to share
Yours double
cannot represent the actual number you are trying to represent due to the loss of precision with double
s. Therefore, the value doesn't change and you don't actually have an overflow.
For types, no int
overflow will result in infinity. Try multiplying this value by 20, for example, and you will see the overflow in action.
source to share