Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string representations of enum values in switch-case

Tags:

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; 
like image 263
Bloke Avatar asked Apr 30 '12 16:04

Bloke


People also ask

Can we use enum in switch case?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.

Are strings allowed in switch case?

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.

Can string be used with enum?

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.

Can a switch statement evaluate an enum?

With the switch statement you can use int, char or, enum types. Usage of any other types generates a compile time error.


1 Answers

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: 
like image 59
Peter Lawrey Avatar answered Oct 12 '22 03:10

Peter Lawrey