Numeric Promotion

Reading Time: 2 minutes

Hi all,

In this post, we will cover numeric promotion in Java. Make sure that you know the bit-length of each primitive types before you proceed.

8-bit 16-bit 32-bit 64-bit
byte short, char int, float long, double

Assume that you add, subtract, multiple, or divide two primitive types. Should you care about the resulting data type? If you add two int values, the resulting value is an int. What if you add an int and a long ? Is the resulting value an int, a long or another data type?

Rules

You need to remember certain rules for numeric promotion.

1. Smaller data types are promoted to a larger data type.

int x = 5;
long y = 67;
long z = x * y; //compiles

Since int is smaller than long, x is promoted to long when * operation is applied. Therefore, the result of (x * y) is a long data type.

int x = 5;
long y = 67;
int t =  x * y; // Type mismatch: cannot convert from long to int.

Previous example will not compile as the result of (x * y) is a long data type and assigned to an int variable.

2. byte, short, and char are for first promoted to int.

int x = 18;
short y = 6;
int z = x / y; // compiles

y is first promoted to int with * operator. The result of (x / y) is int, as both operands are int, and assigned to an int variable.

byte x = 10;
byte y = 3;
byte z = x * y; // Type mismatch: cannot convert from int to byte.

Previous example will not compile as x is first promoted to int. (int * byte) results in int data type.

3. At the end of all promotions, the resulting value will have the same data type as its promoted operands.

short y = 8;
int x = 5;
float z = (y - x) * 3.1f; // compiles

y is automatically promoted to int. Then, (y – x) results in int value, which is promoted to a larger data type float.

Promotion in Compound Operators

Numeric promotions can also be used in compound operators, which enable us to use an implicit cast. Consider the following examples:

int x = 15;
double y = 2.0;
y = y + x; // compiles

The previous example compiles without an issue as x is promoted to double during add operation. The result of (y + x), which is also a double, is assigned to a double variable y.

What if we change the third line with the following?

x = x + y;

It will not compile as we try to assign a double to int variable as stated in compilation error.

int x = 15;
double y = 2.0;
x = x + y; // Type mismatch: cannot convert from double to int.

Hope you enjoyed reading! See you next time…