How do you declare x and y so that x+=y gives a compilation error and x=x+y not?

Try this code

Object x = 1;
String y = "";

x += y; //compile error
x = x + y; //works properly

not entirely sure why this works, but the compiler says

The operator += is undefined for the argument type(s) Object, String

and I assume that for the second line, toString is called on the Object.

EDIT:

It makes sense as the += operator is meaningless on a general Object. In my example I cast an int to an Object, but it only depends on x being of type Object:

Object x = new Object();

It only works if x is Object though, so I actually think it is more that String is a direct subclass of Object. This will fail for x + y:

Foo x = new Foo();

for other types that I have tried.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)