Lesson 4 | Numeric promotions and conversions |
Objective | Describe when and how conversions take place in the evaluation of expressions. |
Numeric Promotions and Conversions
Numeric promotion
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.