byte a = 8; byte b = 8+2; //No compiler error byte c = a+b; //Compiler error
My understanding is: - calculation of numbers(8+2)is done at compiler time; so 8+2=10, which is an int by default and within the range of a byte, will be implicilty cast to byte b with no problem. So no compiler error. - calculation of variables(a+b)or calclulation of numbers and variables(eg.a+2)is done at run-time; so compiler doesn't know the value of a+b but all it knows is the end value of calculation is an int and it needs explicit casting to byte. So compiler error.
Can you confirm my understanding is correct please.
In addition, if the expression is a constant expression of type byte, short, char or int : � A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
8 and 2 are compile-time constants, hence the compiler knows that the result while fit in a byte while a and b which are integers are not.
If you declare a & b as compile-time constants as in:
final int a = 5; final int b = 6; byte c = a+b;
No error is reported by the compiler. [ October 14, 2006: Message edited by: Aniket Patil ]
SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
Joined: Dec 07, 2004
Thanks Anket. That does make sense.
This concept may be added to K&B book(of course, in the next edition) to have a better understanding of primitive casting.