I ran into this question in an interview and couldn’t come up with a solution. I know the vice versa can be done as shown in What does the "+=" operator do in Java?
So the question was like below.
..... x = .....;
..... y = .....;
x += y; //compile error
x = x + y; //works properly
Try this code
not entirely sure why this works, but the compiler says
and I assume that for the second line,
toStringis 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 onxbeing of type Object:It only works if
xis Object though, so I actually think it is more that String is a direct subclass of Object. This will fail forx + y:for other types that I have tried.