When we have an expression that involves values of different data types, the type of the result is determined according to the following table. The table shows the type of the result of an expression of the form a+b, for each possible pair of types for a and b:
a+b | byte | short | int | long | float | double |
byte | int | int | int | long | float | double |
short | int | int | int | long | float | double |
int | int | int | int | long | float | double |
long | long | long | long | long | float | double |
float | float | float | float | float | float | double |
double | double | double | double | double | double | double |
Example:
int a; short b; implies that (a+b) is an expression of type int.
int a; float b; implies that (a+b) is an expression of type float.
float a; double b; implies that (a+b) is an expression of type double.
The table reflects the following rules for the type of an arithmetic expression constituted by an arithmetic operator applied to two operands of different types:
Note: Each time we want to assign the result of an operation to a variable that is of a type smaller than int, we have to insert an explicit type conversion (see below).