My requirement is to perform unassigned sum with short variables in java with out converting in to integer.
Please suggest is it possible to perform unassigned sum or not.
Java doesn't have an addition operator for short
values. If you look at JLS 15.18.2 (Additive Operators (+ and -) for Numeric Types) you'll see that one of the first things that happens is:
Binary numeric promotion is performed on the operands (ยง5.6.2).
That will always convert short
values into int
, float
, long
or double
values, depending on the other operand.
Basically, to perform 16-bit addition, you let the compiler convert both operands into 32 bits, do the addition, and then cast back:
(short) (a + b)
... being aware that this may lose information due to overflow when casting.
See more on this question at Stackoverflow