Java enum examples

What is Enum?

    Enum is a type like class or interface in java. enum is a keyword in java. enum types should be used in place of constants as they are type-safe.
  • The enum declaration defines a class called enum type.
  • The enum class body can have methods and fields
  • Special methods like "values" is added auto-magically by compiler for enum types. values method returns array of all values of enum types.
  • All enum's implicitly extend java.lang.Enum
  • Special methods like "values" is added auto-magically by compiler for enum types. values method returns array of all values of enum types.
 
Let's look at the following example:
 
											
public enum Day{
    SUNDAY, MONDAY
}

										
 
Here SUNDAY and MONDAY are of type Day. This is like creating two objects of type "Day". Compiler internally calls the constructor when creating SUNDAY and MONDAY enum types.
 
Iterating or accessing enum types
  • Special methods like "values" is added auto-magically by compiler for enum types. values method returns array of all values of enum types.
 
											
for( Day p : Day.values() ){
    System.out.println(p);
    System.out.println(p instanceof Day);
}

										
 
output:
SUNDAY
true
MONDAY
true

										
 
Advantages of enum
  • Type-safe
  • Can be used as arguments in switch statement
  • enum values are final and cannot be changed
  • Can be compared using "=="
 
 
Let's dive further and see how to assign values to the enum types:
    Let's say we want to assign day of the week 1 to SUNDAY and 2 to MONDAY. As mentioned above compiler calls the constructor when creating enum types. As we want to provide the value's to the enum types, we will have to provide the constructor.
 
 
package com.visionjava;

public enum DayOfWeek{
	SUNDAY(1), MONDAY(2);
	private int dayOfWeek;
	DayOfWeek(int val){
		 dayOfWeek = val; 
	}
	
	public int getDayOfWeek(){
		return dayOfWeek;
	}
}
 
 
 
So the compiler will call the constructor ( DayOfWeek(int val)  ) when initializing SUNDAY(1) and MONDAY(2). The value "1" and "2" are assigned to dayOfWeek variable in the enum. Remember: enum's are special types like class which can have methods and variables.
 
												
for(DayOfWeek d : DayOfWeek.values()){
    System.out.println(d + " : " + d.getDayOfWeek());
}

											
 
 
Output:
SUNDAY : 1
MONDAY : 2

											
 
Web Analytics