Classes/Objects  «Prev  Next»


Lesson 4Numeric promotions and conversions
ObjectiveDescribe when and how conversions take place in the evaluation of expressions.

Numeric Promotions and Conversions

Numeric promotion

Java uses a conversion technique, referred to as numeric promotion[1], to ensure that numeric expressions are evaluated in a uniform manner. When a binary operation is performed on numeric arguments, the following conversion rules are applied (in order) before a numeric expression is evaluated:
  1. If one of the operands is a double, then the other operand is converted to a double.
  2. Otherwise, if one of the operands is a float, then the other operand is converted to a float.
  3. Otherwise, if one of the operands is a long, then the other operand is converted to a long.
  4. Otherwise, both operands are converted to int values.

Numeric promotion is also applied to the unary operators: +, -, ++, and --. Values of the byte, char, and short types are converted to int values before these operators are applied.
One thing that numeric promotion does not do is convert the results of expressions back to the original operand types. This can lead to some unexpected compilation errors as shown in the NumericConvert program.

Storing Larger Data into a Smaller Data Type

You can still assign a bigger value to a variable that can only store smaller ranges by explicitly casting the bigger value to a smaller value. By doing so, you tell the compiler that you know what you are doing. In that case, the compiler proceeds by chopping off any extra bits that may not fit into the smaller variable.
Though chopping off extra bits will make a bigger value fit in a smaller data type, the remaining bits will not represent the original value and can produce unexpected results.

Compare the previous assignment example (assigning a long to an int) with the following example that assigns a smaller value (int) to a variable (long) that is capable of storing bigger value ranges:
The following is allowed:
int intVal = 1009;
long longVal = intVal;
An int can easily fit into a long because there is enough room for it.

String conversion

Whenever a String object appears as the operand for the + operator, the other argument is automatically converted to a String object. For example, 1 + "23" results in the String "123". Objects are converted to strings via their toString() method. Primitive types are converted to strings via the toString() method of their wrapper class. The null value is converted to the String object "null".

[1]Numeric promotion: The conversion of numeric values to a larger type to support operations on that type.