Hello all! Look at this interesting contradiction... This compiles and runs: int i=1; char _c='c'; _c+=i; System.out.println(_c); This not: int i=1; char _c='c'; _c=_c+i; System.out.println(_c); But the result should be the same if we look at the definition of the operators!!? What do you think? Where is the mistake? Thanks...
Stefano, sun ram: Actually, the JLS 15.26.2 states that the compound assignment given is equivalent to: _c = (char)(_c + i); // legal: result is a char which is different from _c = (char)c + i; // illegal: result is an int
Originally posted by sun ram: compiler will translate _c+=i int _c = (char) _c + i;
As Sun is saying, anytime you use the arithmetic extended assignment operators (+=, -=, *=, etc.), the compiler does an implicit cast back to the type of the variable you're assigning to. Look at these:
The implicit cast can be very important (as you already found). Look at lines 1 and 2 above. Since b + a and s - a return an int value, and we're trying to assign to a byte and a short, respectively, the cast is required. In line 3, the cast is unnecessary, but it is still performed by the compiler. This is an important behavior of the arithmetic extended assignment opeators. Corey
Originally posted by Zac Roberts: So the key idea for the exam would be that the compiler will internally give an explicit cast for the assignment operators, right?
I think I know what you mean, Zac, but it's important to use the correct terms to avoid confusing yourself and others: "For compound assignment operators, the compiler will make an implicit cast to the type of the left-hand side operand."
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck