Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '+' cannot be applied to Object and String

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?

like image 494
Grodriguez Avatar asked Apr 15 '20 15:04

Grodriguez


1 Answers

JLS 15.26.2. Compound Assignment Operators states:

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.

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.

like image 54
Andreas Avatar answered Nov 16 '22 06:11

Andreas