Reputation: 69
For this question i saw a answer like During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value but i didn't understood why because we are also using byte, short, int, char but this statement only saying about int so please explain me and give me an example for this
Upvotes: 1
Views: 1579
Reputation: 719238
Enumeration types were introduced in Java 5, and the switch
statement was enhanced at the same time to allow switching on an enum
value.
That invalidates the quoted statement:
"[d]uring compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value"
... unless it refers to Java 1.4.x or earlier.
What it is saying is that case values must be byte
, short
, char
or int
. (These are the only types whose values can be
promoted to int
... prior to Java 5. Unboxing of wrapper types was introduced in Java 5 as well.)
Of course, that ceased to be true in Java 5. In Java 5 and later, the constants can be enum
values, and in Java 7 and later they can also be String
values (depending on the type of the selector expression).
The other think to note is that you should be reading the relevant version of the JLS for definitive information ... not relying on some StackOverflow question. In this case, the JLS expresses the restriction more simply and more directly.
Reference:
(I couldn't find a public copy of the Java 5 JLS to link to ...)
Upvotes: 2
Reputation: 4432
Java Language Specification is always the best place to check: https://docs.oracle.com/javase/specs/jls/se6/html/statements.html#14.11
Edit: Pasted the link to JLS SE6. Still, JLS is the best place to check.
Upvotes: -1