Java enum with String

In this quick tutorial, how to create String constants using enum, convert String to enum etc.
You can go though complete enum tutorial here.

Let’s create java enum String constants.

Create java enum String

That’s pretty simple.

Access enum by name

You can simply use . operator to access enum but if you have string as enum name, then use of method.

Output:

Week day:TUESDAY
Week day:TUESDAY

Please note that valueOf method takes the String argument as case sensitive.

Output:

Exception in thread “main” java.lang.IllegalArgumentException: No enum constant org.arpit.java2blog.Weekdays.TUesDAY
at java.base/java.lang.Enum.valueOf(Enum.java:240)
at org.arpit.java2blog.Weekdays.valueOf(Weekdays.java:1)
at org.arpit.java2blog.JavaEnumStringMain.main(JavaEnumStringMain.java:7)

Iteratve over all values of Enum with String constansts

You can simply iterate over all String constants using values method.

Output:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY

Let’s give an index to each week days with 1 to 5.You can simply change above enum as below.

Access the index of any weekdays

Output:

Index of Thrusday is: 4

That’s all about Java enum String.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *