Core Java - SPLessons

Java Enum

Chapter 40

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java Enum

Java Enum

shape Description

Java Enum, Enumeration is a feature and data type that will have a fixed number of values. For example Number of days in a week, this enumeration in Java was started in JDK 1.5 and it is one of the excellent feature of Java among generics, autoboxing, unboxing. Actually Enumeration was not available Java, originally it was in C and C++ languages. Enumeration provides better type safety, it will have methods and constructors. Java Enum has the ability to implement more interfaces, but it cannot extend class why because it internally uses the enum class.

shape Example

Java Enum, following is an simple enum example to understand the purpose.
SimpleEnum.java

public class SimpleEnum {
	public enum Season { WINTER, SPRING, SUMMER, FALL }  
	  
	public static void main(String[] args) {  
	for (Season s : Season.values())  
	System.out.println(s);  
	  
	}
}

While creating an Enum Java compiler internally uses the values() method that returns an array containing all the values of the enum.
Output
When compile the code result will be as follows.

WINTER
SPRING
SUMMER
FALL

For more detailed overview on array click here .

Defining Java enum

shape Description

Enum is similar to class so enum can be defined inside the class and outside the class. Following is an example to define the enum outside class.
EnumOutsideClass.java

enum Season { WINTER, SPRING, SUMMER, FALL }  
public class EnumOutsideClass {
	public static void main(String[] args) {  
		Season s=Season.SPRING;  
		System.out.println(s);  
		}
}

Where the developer defined enum outside the class.

enum Season { WINTER, SPRING, SUMMER, FALL }  

Output
Now compile the code result will be as follows.

SPRING

Following is an example to define the enum inside class.
EnumInsideClass.java

public class EnumInsideClass {
	enum Season { WINTER, SPRING, SUMMER, FALL; };  
	public static void main(String[] args) {  
	Season s=Season.SPRING;//enum type is required to access WINTER  
	System.out.println(s);  
	}
}

Here the developer defined enum inside the class as follows. Where the semicolon is an optional.

enum Season { WINTER, SPRING, SUMMER, FALL; };

Output
Now compile the code result will be as follows.

SPRING

Difference between enum and array

Array:

  • An array is a collection of homogeneous elements.
  • An array shares a same name with different index number, which starts from zero.
  • An array is reference type.
  • Enums:

  • An enums are collection of constants, which are recognized with string constants.
  • An enum variables are not initialized then the variables will be initialized automatically from 0 onwards
  • For more detailed overview on array click here .

    Summary

    shape Key Points

    • Enum can be traversed.
    • Enum is freely used in Switch case.