Re: why can't I add two short type variables in java? what is the concept behind it?
Monday, April 13, 2009 02:20 AM
In Java, the default numeric type is integer. Hence when you add up two short type or 1 short type with a numeric constants then the result get converted to premitive integer type.
Another concept to remember is that size of the numeric types grows in following order.
byte-> short -> int ->double
Hence when you want to assign the result (which will be in default int type) to a short there will be a precision loss, hence java wont allow that without programmer's knowledge. If you want to do that explicitly then you have to type cast it like in the below example.
short a = 2;
short b = 3;
short c = (short) (a + b);