How do you declare x and y so that x+=y gives a compilation error and x=x+y not?
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.
It is not possible.
X x = ...;
Y y = ...;
x += y; //1
//equivalent to
x = (X) (x+y); //2
x = x+y; //3
Suppose the type of x+y
is Z. #2 requires a casting conversion from Z to X; #3 requires an assignment conversion from Z to X. "casting conversions are more inclusive than assignment conversions"(1). Therefore, as long as #3 is legal, #2 is legal, and #1 is legal.
On the reverse side, it is possible that #1 is legal, but #3 is illegal, for example
byte x = 0;
int y = 1;
x+=y; // ok, x=(byte)(x+y), cast int to byte is allowed.
x = x+y; // error, assign int to byte
This information is not useful whatsoever; it is a flaw of Java making such surprising differences.
(1) http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.5
int i = 5;
String s = "a";
System.out.println(i+=s); //Error
System.out.println(i+s); // No error
Basically, works for Any object or any non-string primitive and String combination.
I wonder which company it was? :)