I am mystified by the behavior of the Java compiler when assigning primitives to wrapper class references. Please see the code below. The lines with comments don't compile.
I don't understand the logic of why:
- a
bytecan be assigned to aByteorShort, but notIntegerorLongreference - a
shortcan be assigned to aByteorShort, but notIntegerorLongreference - an
intcan be assigned to aByte,Short, orInteger, but notLongreference - a
longcan be assigned to aLong, but notByte,ShortorIntegerreference
I cannot see the pattern. Any insight into this will be really helpful. Thanks.
Byte s5 = (byte)7;
Short s6 = (byte)7;
Integer s7 = (byte)7; // Does not compile
Long s8 = (byte)7; // Does not compile
Byte s9 = (short)7;
Short s10 = (short)7;
Integer s11 = (short)7; // Does not compile
Long s12 = (short)7; // Does not compile
Byte s1 = (int)7;
Short s2 = (int)7;
Integer s3 = (int)7;
Long s4 = (int)7; // Does not compile
Byte s13 = (long)7; // Does not compile
Short s14 = (long)7; // Does not compile
Integer s15 = (long)7; // Does not compile
Long s16 = (long)7;