Java uses the following Numeric Promotion Rules when applying operators to data types:
For the third rule, unary operators are excluded from this rule.
For example, applying ++ to a short value results in a short value.
What is the data type of x * y?
int x = 1; long y = 2;
Follow the first rule.
Since one of the values is long and the other is int, and long is larger than int, then the int value is promoted to a long, and the resulting value is long.
What is the data type of x + y?
double x = 3.21; float y = 2.1;
double? Wrong! This code will not compile! The floating-point literals are assumed to be double, unless postfixed with an f.
We can rewrite the code as
double x = 3.21; float y = 2.1f;
If the value was to 2.1f, then the promotion with both operands being promoted to a double, and the result would be a double value.
What is the data type of x / y?
short x = 10; short y = 3;
Follow the third rule, namely that x and y will both be promoted to int before the operation, resulting in an output of type int.
The result is not double.
public class Main { static public void main(String[] argv) throws Exception { short x = 10; short y = 3; System.out.println(x / y); } }
The code above generates the following result.
What is the data type of x * y / z?
short x = 4; float y = 3; double z = 3;
For the first rule,
x will be promoted to int because it is a short
and
it is being used in an arithmetic binary operation.
The promoted x value will then be promoted to a float
so that it can be
multiplied with y.
The result of x * y will then be automatically promoted to a double, so that it can be multiplied with z, resulting in a double value.