How can I safely downcast an int to short?

Lucas Mendonça :

I have the following Java code:

shortVar = (short) intVar;

But sometimes it's giving me different values than what I expected. What is the best way I can protect my code against this case when it is not able to cast properly and throw an error message?

Little Santi :

In the first place, I'd suggest you should not use the short type: It is not recommended by common Java programming rules (due to a low performance in space, because a short occupies 16 bits, while modern architectures work over 64 bits data).

But, only if you must absolutely use short variables, the right way to ensure you won't be running out of the proper range is this:

    if (intVar <= Short.MAX_VALUE && intVar >= Short.MIN_VALUE)
    {
        short shortVar=(short)intVar;
        ...
    }
    else
    {
        // The cast shall not be safely done.
        ...
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194651&siteId=1