Operator '+' cannot be applied to Object and String
Asked Answered
D

1

11

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?

Dickie answered 15/4, 2020 at 15:14 Comment(5)
I guess value doesnt have to be String. If value is an Integer then i doesnt make sense to add a string to it. Maybye you can try to cast value to stringUnlatch
@Unlatch The expression value = value + suffix is completely legal regardless of the type of value. So it seems to me value += suffix should be legal too.Dickie
wow, i had no idea. I thought that the whole point of different objects was to define rules for what the data can and cannot do. The whole point of having different datatypes and objects is to segregate responsibility to make sure types does one thing, but does it well. I am just baffled that you can mix datatypes like that. Well you learn something everyday :) and Value = value + suffix is the excact same as value += suffix, so i dont dispute the syntax at allUnlatch
Yes but the String type is somewhat special. The + operator here is the "string concatenation operator"; if only one of the operands is a string, the other one is converted to a string before the expression is evaluated. See this section of the JLS.Dickie
Ah i see, didnt know string converted it like that. Thanks for taking the time to reply even after the question has been answered!Unlatch
V
14

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.

Venial answered 15/4, 2020 at 15:25 Comment(2)
JDK (javac) bug then. Thank you for the pointer to the JLS, somehow I missed that.Dickie
15.18.1. String Concatenation Operator + is also relevant to explain why the equivalent statement of value = (Object) (value + suffix) should compile.Tillietillinger

© 2022 - 2024 — McMap. All rights reserved.