Reputation: 33
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?
Upvotes: 3
Views: 98
Reputation: 20195
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))
Even more spread out, we get
double d = p - Math.pow(1,0);
p = (int) d;
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
T
takes two steps:
In the first step, the floating-point number is converted either to a
long
, ifT
islong
, or to anint
, ifT
isbyte
,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 anint
or 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
T
islong
, and this integer value can be represented as along
, then the result of the first step is thelong
valueV
.Otherwise, if this integer value can be represented as an
int
, then the result of the first step is theint
valueV
.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
int
orlong
.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
int
orlong
.In the second step:
- If
T
isint
orlong
, the result of the conversion is the result of the first step....
Upvotes: 5
Reputation: 2266
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
Upvotes: 1