Bits of Java – Episode 5: Numeric Promotion

This week we will talk about numeric promotion. With this term we identify the process for which the compiler promotes a numeric type to a different one.

As you probably already know, this can happen using casting. On the other hand, there are some cases in which the compiler automatically performs numeric promotion, without requiring an explicit casting from your side.

These are the cases in which I would like to focus in this post. Be aware that there could probably be more of such cases with respect to the ones I am going to describe here (I am still studying, so this is not aimed to be an exhaustive discussion on the topic).

That said, let's see two of the cases in which numeric promotion is automatically performed by the compiler.

  • At initialization: to understand this behavior we have first to remind that a numeric literal is by default assumed to be an int by Java, and a floating literal is by default assumed to be a double. These are the reasons why the first two initializations of the following example will not compile.

    Keeping that in mind, when you initialize a numerical variable with a literal that would fit in the range of its default type, but you ask that variable to be of a wider type, the compiler automatically promotes it to the wider type.

    Note that this also works in the other direction, providing that the value fits in the range of the desired type.

  • Numerical expressions: when we execute a mathematical expressions and the operands are of different numeric types, the smaller ones are automatically promoted to the type of the largest operand

    Note that the result of the expression is also expected to be of the type of the operand with the wider type (double in our example), meaning that if you want the result to be of a narrower type you have to explicitly cast it, otherwise the compiler will give you an error.

    Another interesting thing to remember is that byte,short and char are automatically promoted to int, even if there is no operand of type int in the expression.

I think the concept of numeric promotion is one of those things that are very likely to pass overlooked when developing inside an IDE. Now I finally know why we have to cast and where instead the compiler is taking care of that (and why)!

The topic for next week will be logical operators and their short-circuit version.

By Ilenia Salvadori