This snippet of Java code does not result in a compile warning. How can I configure Eclipse to warn in this scenario? If it matters, I'm compiling with 1.8 compliance level.
double dd = 1.1;
int ii = 2;
ii += dd; // this is a possible bug
It does not currently supported in eclipse. There is an Open bug for this as well.
Bug 516084 - Need implicit narrowing of type warning on plus-equals and minus-equals
Background: No warning in compound assignment statement seems a correct behavior as per Java Language Specification section 15.26.2.
15.26.2. Compound Assignment Operators
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
For example, the following code is correct:
short x = 3; x += 4.6; and results in x having the value 7 because it is equivalent to:
short x = 3; x = (short)(x + 4.6);
I believe that there is no warning for this type of conversion because it is the "expected" functionality.
JLS 4.2.4. Floating-Point Operations appears to cover the question.
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).
Later in the same section:
The Java programming language uses round toward zero when converting a floating value to an integer (§5.1.3), which acts, in this case, as though the number were truncated, discarding the mantissa bits. Rounding toward zero chooses at its result the format's value closest to and no greater in magnitude than the infinitely precise result.
Because of this, the following code silently produces Integer.MAX_VALUE:
int intValue = 2;
double doubleValue = 123456789123.7; // this is much larger than Integer.MAX_VALUE.
intValue += doubleValue;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With