Although short
and int
are both integer primitive types, still, they are not the same, and your literal (12
) is, by defaul, interpreted as int
.
short
(primitive) is a 16-bit signed two's complement integer, that can store value from inclusive range [-215, 215-1];
int
(primitive) is a 32-bit signed two's complement integer, that can store value from inclusive range [-231, 231-1].
As you can see, int
can store values from a wider range than short
, which means, that short
is insufficient to store all the values from int
.
Therefore, whenever you do narrowing primitive conversion, compiler will do one of these two:
- It will implicitly do the conversion for you, behind the scenes, IFF the literal value can fit into the range of the target type it is casted to.
- It will ask you to explicitly cast the type IFF the literal value exceeds the range of the target type you want it to be casted to. Why? because, when the literal value exceeds the target range, compiler is unsure about in which specific type you want your value to be casted.. maybe you want to cast it into
short
.. maybe into byte
.. so it's YOU who has to tell this to the compiler.
short a = 32767;
//integer literal 32767 will be automatically converted/casted into "short"
short b = 32768;
//Does NOT compile, as 32768 exceeds "short" range and you need to be explicit, about in which type you want it to be casted, because maybe you want to cast it into the "byte", and not into "short"
byte c = (byte) 32768; //compiles, yet overflows the "byte" type
It is important to understand, that:
Values of the integral types byte, short, int, and long are created from int literals.
So, anytime you do:
long a = 45;
byte b = 2;
short c = 44;
implicit casting applies, and that casting cannot be applied (code will not compile) if the compiler sees, that the literal value exceeds the range of the target type, variable of which, you want to use to store your literal value.
P. S. In your example, explicit casting is semantically redundant, although some may find it nice for syntactical readability purposes.