Table of Contents
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
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public enum Weekdays { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public class JavaEnumStringMain { public static void main(String[] args) { // You can simply use . operator Weekdays wd=Weekdays.TUESDAY; System.out.println("Week day:"+wd.name()); // If you have String as "TUESDAY", you can use valueOf method Weekdays wdVal=Weekdays.valueOf("TUESDAY"); System.out.println("Week day:"+wdVal.name()); } } |
Output:
Week day:TUESDAY
Week day:TUESDAY
Please note that valueOf method takes the String argument as case sensitive.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class JavaEnumStringMain { public static void main(String[] args) { Weekdays wdVal=Weekdays.valueOf("TUesDAY"); System.out.println("Week day:"+wdVal.name()); } } |
Output:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class JavaEnumStringMain { public static void main(String[] args) { for(Weekdays wd:Weekdays.values()) { System.out.println(wd.name()); } } } |
Output:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog; public enum Weekdays { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5); private int index; Weekdays(int index) { this.index=index; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } } |
Access the index of any weekdays
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class JavaEnumStringMain { public static void main(String[] args) { int index=Weekdays.THURSDAY.getIndex(); System.out.println("Index of Thrusday is: "+index); } } |
Output:
That’s all about Java enum String.