How to get enum name using enum value in the lookup method

Enums are very useful feature in Java and you can use when you know all possible values at compile time. In this example we will see how should you get enum name using enum value.

Get enum name using enum value

Here is the enum (WeekDay) we will be using in our example

package com.sneppets.solution;

public enum WeekDay {
	
	SUNDAY(1),
	MONDAY(2),
	TUESDAY(3),
	WEDNESDAY(4),
	THURSDAY(5),
	FRIDAY(6),
	SATURDAY(7);
	
	private int wkDay;
	
	WeekDay(int wkDay){
		this.wkDay = wkDay;
	}

	public int getWeekDay() {
		return wkDay;
	}

	public static WeekDay getWeekDay(int weekDayNo) {
		for(WeekDay wd : WeekDay.values()) {
			if(wd.wkDay == weekDayNo) {
				return wd;
			}
		}
		return null;
		
	}
	

}

In the above example you can see lookup method getWeekDay() defined in the Enum class WeekDay using which you can pass enum value and get enum name as shown below.

For instance, let us pass weekDayNo ‘7’ and lookup for enum name, which results in “SATURDAY”

package com.sneppets.solution;

public class EnumExample {
	
	public static void main (String[] args) {
		int weekDayNo = 7;
		System.out.println("WeekDay : " + WeekDay.getWeekDay(weekDayNo));
	}

}

Output

WeekDay : SATURDAY

You can also use possible enum names on the Enum class and get the enum value as shown below

WeekDay.SATURDAY.getWeekDay()

Output

7

Further Learning

References

 

Leave a Reply

avatar
  Subscribe  
Notify of