In this blog, we will see why we get an error while we perform any arithmetic operations on two operands with type byte or short. we find the following error while compiling the source code in Java.
In the case of type short: Let say we add two variables of type short we get the following error.
Sample code:
class Shortdemo {
public static void main(String arg[]){
short a = 1;
short b = 1;
a = a + b;
System.out.println(a);
}
}
Output:
error: incompatible types: possible lossy conversion from int to short
In the case of type byte: Let say we add two variables of type byte we get the following error.
Sample code:
class Shortdemo {
public static void main(String arg[]){
byte a = 1;
byte b = 1;
a = a + b;
System.out.println(a);
}
}
Output:
error: incompatible types: possible lossy conversion from int to byte.
Hence to avoid such errors occurred at compile time we have to typecast the result type from int type to short/byte as the arithmetic expression or the constant expression on the right-hand side of the assignment is by default of integer type and implicitly we can not convert the data type with higher range to a lower range hence we have to type cast the data type with higher range to the data type of lower range as below.
class A {
public static void main(String arg[]){
short a = 2;
short b = 5;
a = (short) (a + b);
System.out.println(a);
}
}
Output: 7
0 Comment(s)