Conversion between byte, short and char are narrowing conversions.
In the first case byte is not final. So when we assignment is done, it byte will be fist widened to int and then narrowed to char. So this causes the compilation error.
In second case the byte value is finalised and the value assigned to byte can be represented with byte type. So in second case, byte value will be directly widened to char. (int is not invloved in this case).
this should give a compile error in any both the instance because when you multiply a char and a byte, basically what happens is that both 'c' and 'b' are widened to a int. so the result of c*b is an int and hence you are try to store it in a short you get a loss of precision error.
same thing happens if say one number is a decimal number and the other is a integer(e.g c=4 b= 4.5). so when you try to multiply basically what happens is here the integer is widened to a double and the result is a double and hence you have to store it in a double var.
hope this helps
if who i am is what i have, and what i have is lost, then who am i?<br /> <br />SCJP 5.0<br />SCWCD 1.4<br />SCBCD preparing
Joined: Oct 02, 2006
then why could a byte variable implicitly casted to char cause the compiling error, if the byte variable is not final? compiler complains possible loss of precision on c=b; isn't char wider than byte?
Mr Rimzy , the first code gives error at line 1 & 4 because character is unsigned and byte is signed primitive. when you asign a signed byte to unsigned char there is loss of precession.i.e. it will loose the value of leftmost bit which is used to represent the sign. here in this case its 'o'(zero)as positive number and in the program you can change the value of the variable any time. At times it can contain negative number also.
when you make it final,final char c; its a constant and doesn't give error as there is no loss of precession.