+ 1

In Java when we add two byte no.then why it gives error incompatible type

I am not asking about type casting,i want to know about reason i wrote my code like only body i write byte a=100; byte b=10; byte c=a+b; and when i print this code it will give output=Error Incompatible type lossy of conversion from int to byte so whts its meaning why error..?

3rd Sep 2017, 7:17 AM
mohit thakor
mohit thakor - avatar
4 Answers
+ 5
The funny thing is about code like this when adding 2 bytes together and setting to another variable, is that sometimes it works fine (like when I tested it several minutes ago) and other times you get the lossy error. What is happening is that when you perform a calculation on 2 (or more) byte types the compiler will upcast their types to int for the calculation to insure that the type is large enough to hold the resulting value. For instance, if you where to add byte a with a value of 110 and byte b with a value of 35, the result would be 145, witch is greater than the byte type can contain. The error is stating that when you try to implicitly convert an int to a byte that you may end up with an incorrect value due to it being out of range. 145 would wrap and be equal to -111 or (-128 + (145 - 127 -1)). In order to fix this issue you need to explicitly tell the compiler you know what you're doing and cast the result to a byte.
3rd Sep 2017, 8:23 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
You can add 2 bytes together without an error, but it depends on how you're doing it. Can you show your code. Both numbers specifically need to be declared or cast as byte, and be within the range of a byte. byte a = 12; byte b = 15; byte c = a + b; // ok ... sometimes byte a = 4 + 9; // ok byte b = a + 14; // not ok will give an error a is a byte and 14 is an int byte c = (byte)(a + 14) // cast to a byte to fix
3rd Sep 2017, 8:06 AM
ChaoticDawg
ChaoticDawg - avatar
3rd Sep 2017, 7:33 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
when we add two byte numbers, it converts into Int so that's why it showing an error. byte + byte = int byte b1 = 10; byte b2 = 20; byte b3 = b1+b2; // it gives compile time error because b1 + b2 means it convert into int( byte + byte = int) so it shows the error: incompatible types: possible lossy conversion from int to byte. byte + byte = int short + short = int char + char = int int + int = int
18th Aug 2023, 11:57 AM
subhash sahu
subhash sahu - avatar