Enum Types in Java

Enum was introduced in java 5. Enum types in java is a special type of class to define collection of constants. Variables in enum are constants so there name should be in uppercase letters. In java we define an enum type by using the enum keyword. Enum types in java is used to represent a fixed set of constants.

An example of java enum:-

public class EnumTest{
	
	public enum Languages {

		JAVA, PYTHON, RUBY, JAVASCRIPT, PHP, SQL;
	}
	
	public static void main(String[] args){
		
		 System.out.println("example of enum types in java");
		
		 for(Languages languages : Languages.values())

			 System.out.println(languages);
	}
}

output:-
enum types in java

Some special methods are added to the enum class at compile time like static values method in the above example are added by the compiler. The values method returns the array of the enum type in the order in which the enum is declared.

If you want to specify values of enum constants then above example will be modified as:-

public class EnumTest{
	
	public enum Languages {
		
		JAVA("java"), PYTHON("python"), RUBY("ruby"), JAVASCRIPT("javascript"), PHP("php"), SQL("sql");
		
		private String name;
		
		Languages(String name){
			this.name=name;
		}
		
		public String getName(){
			return name;
		}
	}
	
	public static void main(String[] args){
		
		 System.out.println("example of enum types in java");
		
		 for(Languages language : Languages.values())
			 
			 System.out.println("name: "+language+" value: "+language.name);
		 
	}
}

output:-

example of enum types in java
name: JAVA   value: java
name: PYTHON value: python
name: RUBY   value: ruby
name: JAVASCRIPT value: javascript
name: PHP value: php
name: SQL value: sql

Some points about enum

  1. constructor in enum class must be private.
  2. constants in enum are implicitly static and final.
  3. enum can be used in switch statement.
  4. in enum we can compare constants using “==” equality operator.
  5. enums are implicitly final subclass of java.lang.Enum
  6. enum is implicitly static, if it is a member of the class.
  7. abstract methods can also be define inside the enum class.
  8. enum can also implement the interface.
  9. semicolon is optional at the end of enum constant declaration.
  10. enum constructor can be overloaded.
  11. enum can not be declared inside the method.
  12. enum can not be accessed using the new operator because it’s constructor is private.

Leave a Comment