Everybody likes promotions
…of course, I talk about the Java numeric promotions. Probably everyone knows what she/he should do to get promoted, but what about the Java numeric promotions?
A. What does promotion mean?
The numeric promotion represents the automatically made conversion from a smaller numeric type to a wider numeric type when a binary aritmetic operation is made. [So it seems that this does not require hard work for some :D]
Just a small recap about the types and their length can be seen in the below table:
|Type||length in bytes||length in bits|
|byte||1||1 * 8 = ?|
|long||8||∞ * ∞ (reversed)|
|double||8||be my guest|
B. What is required to get a promotion?
Just operands of the same type can be used for a binary operation. In order to achieve that there are some clear rules about how promotions occur:
1. When applying the operator for operands of different types: the smaller numeric type is promoted to the larger number type
2. When applying the operator for an integer value and a floationg point : the integer value is promoted to the floating point value.
3. Byte, short, char are automatically promoted to int when using binary operator.
4. The result of the operation has the type of the operands. [Mind the fact at the time the operator is applied the operands have the same type]
C. Tiny games with promotions
1. Let’s apply the above mentioned rules for the follwing example:
byte byteA = 1; byte byteB = 2; //byte byteSum = byteA + byteB; //short shortSum = byteA + byteB; int intSum = byteA + byteB;
Applying rule number 3 it is clear that the commented out lines of code result in a not very elegant compilation error:
error: possible loss of precision byte byteSum = byteA + byteB; required: byte found: int
2. Apply the rules and say the type .
int intA = 1; float floatB = 2.0f; byte byteC = 3; ____ sum = intA % byteC + floatB;
Yep, first rule number 1 is applied for byteC and the result of intA % byteC would be an integer, then this result is promoted to float and the returned value is float.
3. Let’s try another game. Take the following code:
byte byteA = 1; byte byteB = 2; byteB += byteA;
What happens? If you said “Compilation failure”, please, think again. As I said the promotion is applied only for binary arithmetic operations and += is actually considered a compound assignment operation, but that is another story 🙂
People tend do enjoy promotions ;). I bet you get a promotion every day, so enjoy today!