Numeric Promotion and Casting
Last but not least, switch statements support numeric promotion that does not require an explicit cast. For example, see if you can understand why only two of these case statements compile:
JLS for Java 16 SE, Section 5.1.12 wrote: Forbidden Conversions
Any conversion that is not explicitly allowed is forbidden.
JLS for Java 16 SE, Section 5.2 wrote:In addition, if the expression is a constant expression (§15.29) of type byte, short,
char, or int:
• A narrowing primitive conversion may be used if the variable is of type byte,
short, or char, and the value of the constant expression is representable in the
type of the variable.
• A narrowing primitive conversion followed by a boxing conversion may be used
if the variable is of type Byte, Short, or Character, and the value of the constant
expression is representable in the type byte, short, or char respectively.
The compile-time narrowing of constant expressions means that code such as:
byte theAnswer = 42;
is allowed. Without the narrowing, the fact that the integer literal 42 has type int would
mean that a cast to byte would be required:
byte theAnswer = (byte)42; // cast is permitted but not required
RTFJD (the JavaDocs are your friends!) If you haven't read them in a long time, then RRTFJD (they might have changed!)
RTFJD (the JavaDocs are your friends!) If you haven't read them in a long time, then RRTFJD (they might have changed!)
In addition, if the expression is a constant expression (§15.29) of type byte, short,
char, or int:
RTFJD (the JavaDocs are your friends!) If you haven't read them in a long time, then RRTFJD (they might have changed!)
Albert Kozera wrote:Let me start by saying that I thank you very much for your time. I really appreciate that.
I think your 3 answers have dispelled my doubts.
Albert Kozera wrote:
It seems that this is just a hard JLS definition of "what is allowed and what is not". These kinds of things are the worst to remember.
Albert Kozera wrote:
Thanks again for all yours answers. I'm going back to learning
RTFJD (the JavaDocs are your friends!) If you haven't read them in a long time, then RRTFJD (they might have changed!)
Replace the word "snake" with "danger noodle" in all tiny ads.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|