0

I understand that the result of Math.pow() is a double.

However, why isn't the below code causing an integer overflow when I have explicitly casted the result to an int? Also, why is the result of both 'a' and 'b' the same i.e 2147483647

int a=(int)(Math.pow(2,377));
int b=(int)(Math.pow(2,32));
System.out.println(a);
System.out.println(b);
Karthik Bhat
  • 361
  • 1
  • 4
  • 11
  • Because by casting you're explicitly renouncing any overflow check. – Federico klez Culloca Feb 05 '19 at 15:32
  • 2
    [How does double to int cast work in Java](//stackoverflow.com/a/12515017) – 001 Feb 05 '19 at 15:33
  • @FedericoklezCulloca byte b= (byte)(120+10); System.out.println(b); I do not think that overflow check is renounced here, as the result here is -126, – Karthik Bhat Feb 05 '19 at 15:36
  • 1
    Sorry, for some reason I thought you were asking why it doesn't throw an exception or something like that. Anyway yes, you're renouncing an overflow check. In your `byte` example an overflow *does* happen, as you noted. – Federico klez Culloca Feb 05 '19 at 15:39

1 Answers1

1

If a double is larger than the maximal int value, converting it to int will give you the maximal int value.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142