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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With