This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
short s ='a'; System.out.println(s); The output is 97(guess,the ASCII value of 'a'). Is it right that :Conversions b/w short,char & byte always require explicit cast,even though the value is in range. Then why is it that this code compiles ?.
The code compiles because it meets 3 rules for narrowing conversion: 1. The right operand is a constant expression of type byte, char, short, int. 2. The left opereand is of type byte, char, or short. 3. Value is in range of the left opereand. No cast is required if these 3 rules are met.
When we cast a data type with a lesser size to a bigger one, explicit cast is required. The reason is that when we convert a bigger date type to a smaller one (Byte Size), the bytes will be eliminated to meet the size if the smaller data type and the value won't be correct. If u cast a smaller data type to bigger datatype, say an short to integer, the conversion will be automatic as the bytes will fit in and there won't be any change in the values. And if the values are within the range, there is no need for explicit cast.