Sunday, July 6, 2025

A pitfall with shorts

 There is something important to note about bytes and shorts especially—smaller, whole-number types in Java.


Let’s assume, for example, that we’ve assigned the values 30 and 40 into two different shorts, and we want to add them. A short can hold up to 32767 on the positive end (and down to -32768 on the negative end), so clearly, the result of 30+40 is in-bounds for a short, since it’s just 70.

But they undergo a process called “promotion,” which introduces a trick that most programmers might not even see if they don’t really dig into the language (because almost all whole numbers are ints or longs, and almost all decimal numbers are doubles): the language turns the result of 30 + 40 into an integer, so you cannot save the result into a short without explicitly marking it as such via a cast, and omitting the cast will cause an error.

The reason is actually relatively simple: Imagine I have 20000 (that is, twenty thousand) plus 15000 (fifteen thousand). Either of those is perfectly legal as a short. But the fact that each is legal on its own, as we can see, is not a guarantee that the sum or the product will be legal. 20000 + 15000 is 35000, which is bigger than 32767, so it fits in an int, but not in a short. The result is therefore by default placed into an int, since the sum of the biggest short plus the biggest short does not fit into a short, but does into an int.

To go back to our previous (acceptable) example, to avoid this default behavior, you must explicitly cast the result back into a short, or the compiler will complain.

You must write:

short a = 30;
short b = 40;
short res = (short) a + b;


Omitting the (short) cast—telling the compiler to force the result into a short, because it won’t originally be one—and just doing the following will result in an error, as sensible as this may look:

short a = 30;
short b = 40;
short res = a + b;

At this point, a+b is an int, not a short, and int values can be much bigger (more than 2.1 billion, versus about 32 thousand), so you have no guarantee—unless you make the cast, and deal with the consequences---that the result will be in the type you think it is.

The way you cast something in Java—whether you’re casting object-to-object or primitive-to-primitive— is by including the type you want it to become in parentheses, like so:

short res = (short) a + b;

The “(short)” part of this line of code does the casting of the int (remember, a short plus a short is an int)

 

No comments:

Post a Comment

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...