The following code:
void someMethod(Object value)
{
String suffix = getSuffix();
if (suffix != null)
value += suffix;
[...]
}
compiles without errors in JDK 8 (using -source 1.6), but fails in JDK 6 with the error message:
Operator '+' cannot be applied to java.lang.Object and java.lang.String
While I do understand what the error is about, why does this compile with JDK 8? Is this documented anywhere?
JLS 15.26.2. Compound Assignment Operators states:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
That sentence is the same from Java 6 to Java 14, and has likely never changed since the beginning of Java.
So value += suffix
is the same as value = (Object) (value + suffix)
The Java 6 compiler should not have failed to compile that statement.
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