Let's follow that question with a question? Which ones do you think are valid, and why? I'll be happy to correct you, but take a minute or two and think about it first. Most likely, you already have, but I'd like to see what your thought process is first. Corey
The only one that I think is right would be i=b<<b The reason being that byte b is promoted to ints which assigns without a cast req to i. The rest of the assignments would all be promoted to int's and would therefore require a cast in order to be assigned to short and char. [ June 03, 2002: Message edited by: Rob Petterson ]
I think except s = b* b and c = c + b, everythingelse is correct. These two explicit cast to int, char respectivly. In first Assingment (i = b << b), both b will be cast to int before the operation << takes place. In third assignment, both b and s are converted to int before the operation << i.e s = (short) (s << b) Then an implicit cast to short will take place. The same for last assignment too.
There are, indeed, 3 correct answers. In order to come to this conclusion, you could have simply compiled this code to see which lines caused errors. In short, the following lines are incorrect:
Line 1 is incorrect because the result is promoted to an int, which is unassignable (without a cast) to a short. Line 2 is incorrect for the same reason. The result is promoted to an int, which is unassignable to a char.
The following lines are legal:
In line 1, the result is promoted to an int, but, as you're assigning to an int, this is legal. In lines 2 and 3, compund assignment operators contain an implicit cast to the type of the operand. You can read more about it in the JLS, §15.26.2 Compound Assignment Operators. Therefore, these lines are also legal. I hope that helps clear this up for you, Corey