Contrary to the previous example, if the statements about variables X and I are as follows:
Java code
X = x + I;
However, it is not:
Java code
X + = I;
At first glance, this puzzle may look the same as the previous one. But rest assured that they are not the same. Which statement of the two puzzles must be legal and which statement must be illegal is the opposite.
Just like the previous puzzle, the puzzle also relies on details in the specification for composite assignment operators. The similarities between the two are blocked. Based on the previous puzzles, you may think that the assignment operator is less restrictive than the simple assignment operator. In general, this is correct, but there is such a field where the simple value assignment operator will look looser.
The composite value assignment operator requires that both operands belong to the original type, such as int, or the encapsulated original type, such as integer, but with one exception: if the operand on the left side of the + = Operator is of the string type, it allows the operand on the right side to be of any type. In this case, the operator performs the string join operation. The simple value assignment operator (=) allows the object reference type on the left, which is much looser: You can use them to represent anything you want to represent, as long as the variable on the right side of the expression is compatible with the value assignment on the left.
You can use this difference to solve the puzzle. To use the + = Operator to perform the string join operation, you must declare the variable on the left as the string type. By using the direct value assignment operator, the result of string connection can be stored in an object-type variable.
To be specific and provide a solution to the puzzle, let's assume that we have the following statements before the two values of the puzzle:
Java code
Object x = "buy ";
String I = "valid Java! ";
Simple assignment is legal, because X + I is of the string type, and the string type is compatible with the object assignment:
Java code
X = x + I;
The compound value assignment is invalid because the left side is an object reference type, and the right side is a string type:
Java code
X + = I;
This puzzle is hardly a lesson for programmers. For Language designers, the compound assignment operator of addition should be 'string' type on the right, and 'object' type on the left. This change will eradicate the unintuitive behavior presented by this puzzle.