0

This question :- Make a compound assignment illegal, while simple assignment legal. Is the inverse to a question which I have already solved. Provide declarations to make x += i (compound ) legal and x = x + i (simple) not.

Which can be done by declaring x as short and i as an int. As += contains a hidden cast and x = x + i does not - leading to a compilation error.

I however have been unable to make an assignment where the compound assignment is illegal, while simple assignment is legal. Furthermore to solution to this problem to states :-

Object x = "hello "; String i = "world"; The simple assignment is legal because x + i is of type String and String is assignment compatible with Object. x = x + i; The compound assignment is illegal because the left-hand side as an object reference type other than string x += i;

However I can can compile both with no error?

  • The publication date of the text from which this question was taken was 2005. The solution given may have "worked" then but this has since been fixed in modern java. – Gooze_Berry Oct 02 '19 at 15:42

1 Answers1

0

You're correct and the solution is wrong. It's completely legal to say Object+String, because that allows you to get a String. It's also legal to say Object += String, because that is the equivalent of Object = (Object)(Object+String), which is valid since Object+String (as said before) is String, and this can be upcast (widened) to Object.

If you want x = x + i to be legal and x += i illegal, that is actually impossible. As seen in this answer, x += i is equivalent to x = (type of x) (x + i). Now, if x = x + i is legal, that implies that the type of x is a superclass or the same class as the type of x + i. That also implies that for x += i, the type cast will never fail iff x = x + i is legal, as no narrowing conversions will occur if x = x + i is legal.

tl;dr: The logic is a bit circular, but it's essentially saying that if x = x + i succeeds without casting, then it will also succeed with casting in x += i, since you had to check for fitting to type of x in the first statement anyways.

Avi
  • 2,611
  • 1
  • 14
  • 26