A colleague of mine asked this question to me and I am kind of confused.
int i = 123456;
short x = 12;
The statement
x += i;
Compiles fine however
x = x + i;
doesn't
What is Java doing here?
int i = 123456;
short x = 12;
x += i;
is actually
int i = 123456;
short x = 12;
x = (short)(x + i);
Whereas x = x + i is simply x = x + i. It does not automatically cast as a short and hence causes the error (x + i is of type int).
A compound assignment expression of the form
E1 op= E2is equivalent toE1 = (T)((E1) op (E2)), whereTis the type ofE1, except thatE1is evaluated only once.
Numbers are treated as int unless you specifically cast them otherwise. So in the second statement when you use a literal number instead of a variable, it doesn't automatically cast it to the appropriate type.
x = x + (short)1;
...should work.
char ch = '0'; ch *= 1.2;now ch is'8';)