hi! for the following statement System.out.println(Math.roundInteger.MAX_VALUE+2200)); the output is -2147482472 but the API says If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE can some one explain the output
hi! i got u. System.out.println(Math.round(Integer.MAX_VALUE+2200f)); gives Integer.MAX_VALUE thanx very much. madhur.
Joined: Aug 03, 2002
Well you got some enlightenment, but not exactly the right kind. Ok, take a look at the following:
and it's results
The addition of 2200 to Integer.MAX_VALUE overflows (silently) giving a negative result. That is the argument that Math.round goes to work on. What's interesting is what Math.round will it call? The float version or the double version? I just found that it is calling the float version of Math.round. -Barry [ September 01, 2002: Message edited by: Barry Gaunt ]
Hi Barry: Is (Integer.MAX_Value + 2200) not an integer? Why is Math.round() treating it as floating point integer? And why is it treating it as an float rather default double? Thanks Barkat
Joined: Aug 03, 2002
Hi Barkat, I did not say Integer.MAX_Value + 2200 was not an int. There are two versions of Math.round one taking a float, the other taking a double. Now if you print the values of Math.round((float)(Integer.MAX_Value + 2200)) and Math.round((double)(Integer.MAX_Value + 2200)) you get different values. But the one you get from Math.round((Integer.MAX_Value + 2200)) is the same as the one you get Math.round((float)(Integer.MAX_Value + 2200)). That implies to me that the compiler selects the float version of Math.round in this case. As to why the compiler calls the the float version, my guess is that it is the first possible widening conversion from an int to a floating point representation. I'm checking what the JLS says about this, but I do not yet fully understand what it is saying. Maybe someone can take a look at what byte code is actually produced.
It looks to me that on line 21 of the main method, int Math.round(float) is being invoked. As always I stand to be corrected as part of my learning experience. -Barry [ September 02, 2002: Message edited by: Barry Gaunt ]