I came across something that I didn't fully understand earlier and wondering if someone may be able to shed some light on it.
There is a class file with many static final variables, then they're case to the same type as in the declaration and I wonder why.
So as an example we have:
public static final short A_CONST_VALUE = (short)12;
Thanks.
There is no problem in this line
public static final short A_CONST_VALUE = (short)12;
orpublic static final short A_CONST_VALUE = 12;
if the literal you are specifying is within the range ofshort
which is -32,768 to 32,767. So if you were this linepublic static final short A_CONST_VALUE = 32768;
and compile you will get error "possible loss of precision found: int, required : short" but instead if you writepublic static final short A_CONST_VALUE = (short)32768;
the value of A_CONST_VALUE will be type casted toshort
and it's value will be -32768 ie it will cycle back.So as long as the literal is within the range of short, we don't need that typecast.Also the literal that we are assigning to A_CONST_VALUE is not any datatype its just a numeric value and it should lie within the range -32,768 to 32,767 because A_CONST_VALUE is a short dataype. Nuts n bolts of primitive datatype in java