Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 382
knshn Avatar asked Nov 15 '11 14:11

knshn


2 Answers

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.

like image 174
skynet Avatar answered Oct 17 '22 22:10

skynet


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

like image 41
irreputable Avatar answered Oct 17 '22 22:10

irreputable