In addition to the elevation of bytes and shorts to int, Java defines several type promotion
rules that apply to expressions. They are as follows. First, all byte and short values are
promoted to int, as just described. Then, if one operand is a long, the whole expression
is promoted to long. If one operand is a float, the entire expression is promoted to float.
If any of the operands is double, the result is double.
The following program demonstrates how each value in the expression gets
promoted to match the second argument to each binary operator:
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
Let’s look closely at the type promotions that occur in this line from the program:
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the result of the subexpression
is float. Next, in the subexpression i / c, c is promoted to int, and the result is of type
int. Then, in d * s, the value of s is promoted to double, and the type of the subexpression
is double. Finally, these three intermediate values, float, int, and double, are considered.
The outcome of float plus an int is a float. Then the resultant float minus the last
double is promoted to double, which is the type for the final result of the expression.
0 comments: