Next: Assignments between different primitive Up: Unit 04 Previous: Predefined static methods for

## Expressions that involve different primitive numeric types

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:

• If the type of one operand denotes a subset of values denoted by the type of the other operand, then the type of the expression is the one with the larger set of values.
• If one operand is of an integer type (byte, short, int, long) and the other is of a floating point type (float, double), then the result of floating point type.
• Each time an arithmetic operation is performed on primitive types that are smaller than int (i.e., byte or short), then the compiler inserts a conversion of the types into int before executing the operation. Hence, the result will be at least of type int.

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

Next: Assignments between different primitive Up: Unit 04 Previous: Predefined static methods for