Why is my simple 3-line displayimg error? | SoloLearn: Learn to code for FREE!

+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/22/2020 3:02:10 PM

Yuvraj Singh

3 Answers

New Answer

+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

You try to pass an int value to a byte, thats why. Check the following. byte a = (byte)5; byte b = (byte)10; byte c = (byte)(a+b); OR change just this one byte c = (byte)(a+b);

+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).