you should use floating-point value of 2
instead of integer in this line:
int b = (int) Math.ceil(a / 2f);//also you can use "2.0" or "2d" instead of "2f"
your version uses int
division (which produces int
value of 2
) and 2f
constant forces to use floating-point division and promote a
value to float
(after it division produces float
value of 2.5
)
It is possible because of JLS spec for Multiplicative Operators:
Binary numeric promotion is performed on the operands (§5.6.2)
And that is how numeric promotion works for int
and float
division operands in our case:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.