hi friend, refer K&B book pg:148 first 3 lines of the last paragraph. the result of an expression involving anything int sized or smaller is always an int. consider the following example and compare it with that u have provided. byte a=100; byte b=50; byte c=a+b; now the answer is 150 which is clearly out of range for a byte,but well with in the range of an integer.so we need an explicit cast in this case. regards raja
The example which i took is from K&B book only, my question is it says when we say >> byte b = 27; compiler automatically casts it , right ?, why didnt we cast here explicitely ??, 27(literal integer) won't fit in to byte , right??
well i think ppl yet answered haven't underestood ur questn.....right??? well if i've understood it correctly then the simple answer is : byte b = 27 //1 legal byte b = 127 //2 legal byte b = 128//3 illegal byte b = 27d //4 illegal byte b = 27f //5 illegal
now life is easy max value of a byte primitive can be 127. all of them above are compile-time constants, so the compiler is clever enough to to allocate only 128 bits for the variable in the memory(stack or heap) it dosen't asks us to do a explicit cast, required otherwise. you can see at line 3,4,5 since the compiler can see that even if allocates 128 bits, its not suffice.
in ur case: byte c = a + b;//not legal where a and b are byte primitives byte c = (byte)(a + b); //explicit cast req. since a and b are not compile-time constants we have to do an explicit cast
well again if u declare a and b as final(actually as constants), then again u'll see u dont require an explicit cast. As in:
final byte a = 7; final bute b = 8;
byte c = a + b; //no need to do explicit cast as 'a' and 'b' are now compile-time constants
HI Amit, Well I think I did declared a and b as compile time constants but I think when I do (a + b) the result is int, because of this I need to explicitly cast it to byte. By the way I didn't understand why this will work with out casting if I declare them as final??