on executing :
int p=-2147483648;
p-=Math.pow(1,0);
System.out.println(p);
p-=1;
System.out.println(p);
Output: -2147483648
2147483647
So why doesn't Math.pow() overflow the number?
We start the discussion by observing that -2147483648 == Integer.MIN_VALUE (= -(2³¹)).
The expression p -= Math.pow(1,0) has an implicit cast from double to int since Math.pow(...) returns a double. The expression with an explicit cast looks like this
p = (int) (p - Math.pow(1,0))
Ideone demo
Even more spread out, we get
double d = p - Math.pow(1,0);
p = (int) d;
Ideone demo
As we can see, d has the value -2.147483649E9 (= -2147483649.0) < Integer.MIN_VALUE.
The behaviour of the cast is governed by Java 14 JLS, §5.1.3:
5.1.3. Narrowing Primitive Conversion
...
A narrowing conversion of a floating-point number to an integral type
Ttakes two steps:
In the first step, the floating-point number is converted either to a
long, ifTislong, or to anint, ifTisbyte,short,char, orint, as follows:
If the floating-point number is
NaN(§4.2.3), the result of the first step of the conversion is anintor long 0.Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value
V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:
If
Tislong, and this integer value can be represented as along, then the result of the first step is thelongvalueV.Otherwise, if this integer value can be represented as an
int, then the result of the first step is theintvalueV.Otherwise, one of the following two cases must be true:
The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type
intorlong.The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type
intorlong.In the second step:
- If
Tisintorlong, the result of the conversion is the result of the first step....
Please note that Math.pow() operates with arguments of type Double and returns a double. Casting it to int will result in the expected output:
public class MyClass {
public static void main(String args[]) {
int p=-2147483648;
p-=(int)Math.pow(1,0);
System.out.println(p);
p-=1;
System.out.println(p);
}
}
The above produces the following output:
2147483647
2147483646
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With