This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The compiler does narrow the byte b = 3; as it is doing in line 1. However the last line of your code appears to be the real problem here because you are trying to add to bytes which will result in an int so you cannot assign it to byte type variable. Looking at your code, it seems you might get a compile error in line 2 because you define variable b which has already been defined in line 1.
Joined: May 18, 2008
thank you ,Paul.
what I don't understand it is (byte b = 3) 3 is an int , but we can assign it to byte type variable .
and byte + byte is an int too,why we cannot assign it to byte type variable？
the problem here is that for the compiler it makes a difference if you assign an integer literal like "3" or if you assign an expression like "b + c". For you it may be obvious that "b + c" in this could be stored into a byte variable without loss of information but for the compiler the value of such an expression isn't known at compile time so it has to assume that the expression "b + c" could lead to an overflow if you try to put it in a byte variable. Therefore you have to explicitly cast it to a byte telling the compiler that you know there could be loss of precision and that's OK for you
Joined: Feb 16, 2008
Maybe I didn't get the point, Jack. Anyway, Pawni Jain is right. In addition I can add that when declaring a variable like byte b = 3 (or - in case of byte type - with any other value <= 127) the compiler is smart enough to notice that this number will fit into 8-bit byte so it narrows this - otherwise int literal - implicitely to byte.
Joined: May 18, 2008
Thank you all, and thank Marco
For you it may be obvious that "b + c" in this could be stored into a byte variable without loss of information but for the compiler the value of such an expression isn't known at compile time .