+ 10
final byte variable
byte a = 1; byte b = 2; byte c = a + b; //error: incompatible types: possible lossy conversion from int to byte System.out.println(c); //add final final byte d = 1; final byte e = 2; byte f = d + e; System.out.println(f); //Output: 3 Why the code compile success when I mark byte variable as final ?
5 ответов
+ 3
I believe it is giving that error because of a unary numeric promotion (using the + operator).
When I ran your code and declared your first set of data types (a, b ,c) as an integer while keeping the rest of your code as is (I added 'final' as you had commented), it compiled and ran successfully for me.
Check out the link I have posted below the comment. You may have to dig a bit to understand, but I am sure it will be worth the reference.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
+ 8
Thanks Apocryphon and Ipang.
I find some description about this issue.
https://stackoverflow.com/questions/32005417/why-does-adding-final-bytes-result-in-a-byte-but-adding-non-final-bytes-results
https://stackoverflow.com/questions/15655012/how-final-keyword-works
Actually, I still can't understand.
+ 3
@Kuanlin Chen,
I tried this and it worked on Code Playground:
byte c = (byte)(a + b);
But honestly, I don't have any idea why or how, the a, b, c are all byte but requires casting.
+ 1
Mb 'cause type byte is too short?
- 3
What??????!!!!!!!