1
visibility
class IntegerGroupAddition
{
public static void main(String args[])
{
long L = 30;
int i = 50;
short s = 60;
byte b = 70;
int sum = L + i + s + b;
System.out.println(“Sum = ” + sum);
}
}
Sum = 210
Sum = 128
Sum = 127
Program will not compile.
sum is an integer variable. The result of L + i + s + b will be long as i, s, b are automatically casted to long while adding them to L. But the result of this addition is stored in sum which is of type int. This leads to type mismatch. So the program does not compile. In order to avoid this explicitly cast L or L + i + s + b to int as shown below.
int sum = ((int)L) + i + s + b;
// or
int sum = (int) (L + i + s + b);