Reputation:
I perfectly write my java code but this ERROR (internal.java:21: error: incompatible types: possible lossy conversion from int to byte) bringing repeatedly. but a,b,c variables are byte data type. So please help by solve this problem. And why this problem bringing me. please explain this problem technically.
I already use type conversion such as a=(byte)(c+b) and it's work. But why this error comes. So please explain this error.
class Inter {
public static void main(String[] args)
{
byte a = 20 , b = 10, c = 20 ;
if(a<=b && a<=c)
{
a = c+b;
System.out.println(a);
}
else if(b>=c)
{
a +=b;
System.out.println(a);
}
else
{
a+=c;
System.out.println(a);
}
float t = (a/40.0f)*10;
System.out.println("internal mark is : "+ t);
}
}
internal.java:21: error: incompatible types: possible lossy conversion from int to byte a = (byte)c+b; ^ 1 error
Upvotes: 0
Views: 900
Reputation: 665
In Java a byte can hold values ranging from -128 to 127, if you have passed values more than 127 which will cause the byte to overflow and can't hold it so it will cause into the exception, but when you are casting the addition or larger value than 127 to byte it will try to get the negative range value -128 and from there it goes on repetitive, like if byte a=10; and byte b=120; then byte c=(byte)(a+b); will return you -126 as it is 3 numbers more than 127, now it goes to -128,-127 and -126 value will be taken. So to get this value loss fixed compiler will force you to take c as int so that there will be no loss in the actual value which you wanted.
Upvotes: 0
Reputation: 4582
byte
in java is 8 bit size, which has a limit of -128 to 127. So suppose a scenario like if a = 127 and b = 127. So if you add a and b the value is 254, which byte
data type can not hold.
So when you add two byte
type variable, output is automatically converted to int
. So it should be assigned by int
.
So assigning the output of a+b to a byte by implicit casting, will overflow and results won't be correct.
Upvotes: 0