Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 1
Why is my simple 3-line displayimg error?
This is the program...it's displaying "possible lossy conversion", now, I knkw that the '+' operator changes byte to int, but it shouldn't br the case here.? https://code.sololearn.com/cTxTDr3kYPfA/?ref=app
2 Answers
+ 7
Why are we doing a casting in sum, subtracting division and multiplication? First, if you don't know what I mean by casting, let's just say it's this line of code (in the case of addition):
byte c = (byte) (a + b);
The fundamental reason is that the addition, subtraction, multiplication and division of two bytes returns me an integer; then I have to transform it to save it back to a byte type
+ 2
Byte is not a type intended for doing arithmetic so, when you try to sum the values, the compiler convert (or promote) the type to a more convenient one (integer).
Another thing you can do is declare both variables a and b as final so the compiler will know the values won't change:
final byte a = 5;
final byte b = 10;
byte c = a + b;
Then the only thing that you need to take care of is not using values that sum more than the range of the byte (-128 to 127).