Could someone explain me, why a
is equals 2'147'483'647
?
int a = (int)(3434 * 2353253.0)
Why is this "sticking to Integer.MAX_VALUE" happening?
I expected some integer overflow behavior and a result of -508'863'790
(openjdk 11.0.16.1 2022-08-12)
It's happening because the Java language says it must. See section 5.1.3, Narrowing Primitive Conversion.
Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V using the round toward zero rounding policy (§4.2.4). Then there are two cases:
a. If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.
b. Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.
• Otherwise, one of the following two cases must be true:
a. 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 or long.
b. 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 or long
This last clause is what you are witnessing in action.