+ 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 ?

1st Sep 2017, 7:55 AM
Corey
Corey - avatar
5 Réponses
+ 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
1st Sep 2017, 9:26 AM
Apocryphon
Apocryphon - avatar
8th Sep 2017, 9:44 AM
Corey
Corey - avatar
+ 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.
2nd Sep 2017, 5:57 AM
Ipang
+ 1
Mb 'cause type byte is too short?
17th Feb 2018, 11:47 PM
Charm Freak
Charm Freak - avatar
- 3
What??????!!!!!!!
29th Oct 2017, 7:26 AM
Nirnay