Type Promotion (Computer Programming)
There is another place where certain type conversions may occur. In an expression, sometime the precision required of an intermediate value will exceed the range of either operand.
For example: Java Programming
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, Java automatically promotes each byte, short, or char operand in to int when evaluation an expression. This means that the subexpression a*b 50*40, is legal even though a and b are both specified as byte.
Java can promote data types when it evaluates an expression. A byte can be promoted to a float, a char to an integer, a short to a double, an int to a float, and a float to a double.
For example: Java Programming
class Promote
{
public static void main(String[] args)
{
byte b = 42; //promoted to float
char c = ‘a’; //promoted to integer
short s = 1024; //promoted to double
int I = 50000; //promoted to float
float f = 5.67f; //promoted to double
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);
}
}
These automatic promotions can cause unexpected compile-time errors.
For example: Java Programming
byte b = 50;
b = b*2; //Compile-time error: Cannot assign an int to a byte
This is because, first compiler will promote all byte types in to int when evaluation expression. Therefore result of 50*2 is 100 and it is integer and you are about to assign this integer in to a byte variable b without casting. Therefore, an explicit cast needed (b = (byte) b*2;) To remove these issues, there are type promotion rules. They are as follows;
First all byte, short and char values are promoted in to int. Then, if oneoperand is a long, the whole expression os promoted to long. If one operand is a float, the entire expression is promoted to float. If any operands is double, the result is double.