Why is it not possible to use enum values as strings in a switch case? (Or what is wrong with this:)
String argument; switch (argument) { case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ? // something break; case MyEnum.VALUE2.toString(): // something else break;
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.
Strings in switchIt is recommended to use String values in a switch statement if the data you are dealing with is also Strings. The expression in the switch cases must not be null else, a NullPointerException is thrown (Run-time). Comparison of Strings in switch statement is case sensitive.
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
With the switch statement you can use int, char or, enum types. Usage of any other types generates a compile time error.
You can only use strings which are known at compile time. The compiler cannot determine the result of that expression.
Perhaps you can try
String argument = ... switch(MyEnum.valueOf(argument)) { case VALUE1: case VALUE2:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With