In many expressions, the type of one operand will be temporarily promoted to the larger type of the other operand.
The above example is a special case of the overall concept of implicit type conversion. In virtually any arithmetic operation, the data types of the operands will be temporarily converted to the data type of the largest operand. For example, if we are multiplying an integer by a float, the integer will be promoted to a float for the duration of the evaluation of the expression.
As we see here, we are multiplying an integer with a value of 10 by a float with a value of 2.0. In this case, the int is promoted to a float, so the 10 becomes 10.0. Once the expression has been evaluated giving us a float result of 20.0, the variable x goes back to being an int. This implicit type conversion helps to ensure that no precision is lost as part of the operation.
Implicit Arithmetic Type Conversion Hierarchy
Example Implicit Type Conversions
|Expression||Implicit Type Conversion||Expression's Type||Result|
|-x||x is promoted to int||int||5|
|x*-2L||x is promoted to long because -2L is a long||long||10|
|8/x||x is promoted to int||int||-1|
|8%x||x is promoted to int||int||3|
|8.0/x||x is promoted to double because 8.0 is a double||double||-1.6|
Here are some examples of real world implicit type conversions. For each example, assume that x is defined as a short int with a value of -5.
- In the first case, even though x is the only operand, it is promoted to int for the operation because int is the fundamental data type for most operations.
- In the second case, x is promoted to long since the literal is explicitly specified as a long, which is larger than short.
- In the third case, we are dividing an int by a short, so the short is promoted to int.
- The same holds true for the fourth case.
- The last one has x promoted to double because the numerator is type double. Since we didn't explicitly specify the numerator as a long: 8.0L, the compiler assumes it is the largest unmodified floating point type which is double, as opposed to a modified type: long double.