Tag Archives: enum

Java : Enumeration handling


An enum is a data type (same as user-defined classes) that defines a variable with predefined constants. To access/assign value to enum variable, it must be equal to one of the values that have been predefined for it.

Points to remember:

  • The enum added in java  5.
  • The enum keyword is used to define enum type.
  • Each enum constant are by default public static final instance variable.
  • Two enumeration constants can be compared for equality by using == relational operators.
  • The name of enum type’s fields should be in UPPERCASE because they are constant.
  • Use enum types any time when you need to represent a fixed set of constants.
  • Semi colon is optional in side enum type if no any other member.
  • If constructor and methods used inside enum then semi colon required.
  • All enum implicitly extends java.lang.Enum class. Because java doesn’t allow extends of more than one parent class, so an enum can not extend anything else.
  • enum can implement many interfaces.
  • toString() method is overridden inside java.lang.Enum class which returns enum constant name.
  • enum constant can also use in switch case statement.

Implicit methods of java.lang.Enum

Below are implicit methods of enum class.

  • values() method can be used to return all values present inside enum.
  • ordinal() method return index of each enum constant, same as array index.
  • valuesOf() method returns the enum constant of specified string value, if exists.

In the below examples, you will see the use of these methods.

enum Month{
JANNUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};

enum with constructor and method definition.

enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
	};

Example

public class EnumTest {
	enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
public void showMonthName() {
System.out.println("Month Name :"+this.monthName);
}
};
	public static void main(String[] args) {
		//values method return array of constants of type MonthDetail
		for(MonthDetail monthDetail:MonthDetail.values())
		{
			monthDetail.showMonthDetail();
		}

MonthDetail  month=MonthDetail.DECEMBER;
//two enumeration can be compared by == relational operators
if(month==MonthDetail.DECEMBER)
{
//call method of enum to getName of enumerated month
month.showMonthName();
}
}

Output


1 : January
2 : February
3 : March
4 : April
5 : May
6 : June
7 : July
8 : August
9 : September
10 : October
11 : November
12 : December

December

Enumeration with switch and case

As in switch case value always allow constant value and enumeration is constant so we can use case values as enumeration. You can refer to the below example where case values use as PLUS, MINUS, MULTIPLE and DIVIDE enum constant values.

package enm;

public class Calculator {
	public enum Operator {
		PLUS, MINUS, MULTIPLY, DIVIDE
	}
	public static double Calculate(int left, int right, Operator op) throws Exception {
		double result = 0.0;
		switch (op) {
		case PLUS:
			result = left + right;
			break;
		case MINUS:
			result = left - right;
			break;
		case MULTIPLY:
			result = left * right;
			break;
		case DIVIDE:
			result = (double) left / right;
			break;
		default:
			throw new Exception("Couldn't process operation: " + op);
		}
		return result;
	}

	public static void main(String[] args) {
		try {
			System.out.println(Operator.PLUS + " : " + Calculate(20, 10, Operator.PLUS));
			System.out.println(Operator.MINUS + " : " + Calculate(20, 10, Operator.MINUS));
			System.out.println(Operator.MULTIPLY + " : " + Calculate(20, 10, Operator.MULTIPLY));
			System.out.println(Operator.DIVIDE + " : " + Calculate(20, 10, Operator.DIVIDE));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}

Output


PLUS : 30.0
MINUS : 10.0
MULTIPLY : 200.0
DIVIDE : 2.0

Enumeration Exception

while using enumeration generally two types of exceptions need to handle.

[Solved] java.lang.IllegalArgumentException: No enum constant


Pre-requisite :  Java : Enumeration Handling

Below is example of enumeration by using all implicit methods of enumeration.
Here used wrong value of enumeration as “Saturday” while using month name here that’s why causing this issue.

package enm;

public class EnumTest {

	enum Month{JANNUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER};
	enum MonthDetail{
		JANNUARY("January",1),
		FEBRUARY("February",2),
		MARCH("March",3),
		APRIL("April",4),
		MAY("May",5),
		JUNE("June",6),
		JULY("July",7),
		AUGUST("August",8),
		SEPTEMBER("September",9),
		OCTOBER("October",10),
		NOVEMBER("November",11),
		DECEMBER("December",12);

		public String monthName="";
		public int index;

		//Constructor will always private
		private MonthDetail(String monthName,int index)
		{
			this.monthName=monthName;
			this.index=index;
		}
		//Method
		public void showMonthDetail()
		{
			System.out.println(this.index +" : "+this.monthName);
		}
	};
	public static void main(String[] args) {
		for(Month month:Month.values())
		{
	    //Add one because by default enum indexing start from 0
		System.out.println((month.ordinal()+1) +" : "+month.name());
		}
		//Every enum Class provide values method to get list of enums
		for(MonthDetail monthDetail:MonthDetail.values())
		{
			monthDetail.showMonthDetail();
		}

		try
		{
		MonthDetail mnth=MonthDetail.valueOf("Saturday");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Output


1 : JANNUARY
2 : FEBRUARY
3 : MARCH
4 : APRIL
5 : MAY
6 : JUNE
7 : JULY
8 : AUGUST
9 : SEPTEMBER
10 : OCTOBER
11 : NOVEMBER
12 : DECEMBER
1 : January
2 : February
3 : March
4 : April
5 : May
6 : June
7 : July
8 : August
9 : September
10 : October
11 : November
12 : December
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant enm.EnumTest.MonthDetail.Saturday
    at java.lang.Enum.valueOf(Enum.java:238)
    at enm.EnumTest$MonthDetail.valueOf(EnumTest.java:1)
    at enm.EnumTest.main(EnumTest.java:49)

Solutions:
Always use valid constant values to resolve this issue and while trying to call this enum.valueOf() method always handle exception so that any exception happen then your program will not terminate.

try {
 MonthDetail mnth=MonthDetail.valueOf("August");
} catch(Exception ex) {
ex.printStackTrace();
}

To learn more on Enumeration follow below link: Java : Enumeration Handling