In my recent work, I met a question, which is about the numeric promotion of some operands. The following is the demo code:
int num1 = 9999999;
int num2 = 65536;
double result = num1*num2*1.0;
In my opinion, I thought both of num1 and num2 will be automatically promotion to double and then calculate the result as one of the operands is a double, while the result shocked me. I got a negative number. And then I look into the JLS, it also says it should do the numeric promotion, see below:
"If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).
Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. (If the other operand is not a float, it is first widened to type float by numeric promotion.)"
And if I change the result to 1.0*num1*num2, it will give me the right answer. Could anybody tell me what the hell is this.
No, the result of num1 * num2
is promoted to double. Your statement is equivalent to:
double result = (num1 * num2) * 1.0;
So with promotion, that would be:
int firstMultiplication = num1 * num2;
double promoted = firstMultiplication;
double result = promoted * 1.0;
Basically, this is just a matter of operator precedence. Numeric promotion happens to operands - not every expression which was involved in evaluating that operand to start with.
See more on this question at Stackoverflow