Best shorthand questions in November 2011

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

35 votes

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

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.