Automatic type promotion in java

Java automatically promotes each byte or short operand to int when evaluating an
expression. Means automatically promotes lower data type to higher data type.

For example,
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;

The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, This means that the sub-expression a * b is performed
using integers—not bytes.

Example Type Promotion Rules :
double result = (f * b) + (i / c) - (d * s);

f is float variable, b is byte variable, i is int variable, c is char variable, d is double and s is sort
variable.

first result of the sub expression f * b is of type float.
Second result of the sub expression i / c is of type int.
Third result of the sub expression d * s is of type double.
The outcome of float plus an int is a float.

Then the resultant float minus the last double is to double, which is the type for the final result of
the expression.

Problem : Some time give compile time error.
For example :
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
Solution : Explicit Cast.
For example,
byte b = 50;
b = (byte)(b * 2);

Comments