Enum Types in Java

Java provided Enum types are very powerful than other programming languages. Following are the main points one should remember about java enum types.

  • enum type is defined using enum keyword
  • enum type is a special data type that allows a variable that consist of a predefined constants
  • enum declaration defines a class
  • enum class body can include constructors, methods and fields. Compiler automatically adds some special methods when it creates an enum
  • enum constants are implicitly static and final
  • enum internally extends Enum class. enum may implement several interfaces but can’t extend any class
  • enum improves type safety
  • java implicitly includes values() method when it creates an enum. The values() method returns an array containing all the values of the enum
  • It is available from jdk 1.5 onward

Following is the simple example which uses enum type variables and in main method list is retrieve and printed on console.

public class EnumTest {
public	enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY,FRIDAY,SATURDAY, SUNDAY };
	public static void main(String[] args) {
		for(Day d : Day.values()){
			System.out.println(d);
		}
	}
}

Output of this program is listed below:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Another program to define your own method and initialize enum constant variables.

public enum Greetings {
	BIRTHDAY("Happy Birthday"), MORNING("Good Morning"), ANNIVERSARY("Happy Anniversary"), MOTHERDAY(
			"Happy Mother Day");

	private String msg;

	Greetings(String msg) {
		this.msg = msg;
	}

	public String greetingMsg() {
		return this.msg;
	}
}
public class EnumTest {
	public static void main(String[] args) {
		for(Greetings g : Greetings.values()){
			System.out.println(g + " : "+g.greetingMsg());
		}
	}
}

Output of this program is listed below:

BIRTHDAY :  Happy Birthday 
MORNING : Good Morning
ANNIVERSARY : Happy Anniversary
MOTHERDAY : Happy Mother Day

Video Tutorial

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.