Enums In Java - with Examples, Advantages & Use Cases

Note: You might not understand enums completely while reading for the first time. Please try out atleast few problems after reading and then read again for a complete understanding.

 

An enum type (or enumerated type) is a type whose fields consist of a fixed set of constants. Eg: Months in a calendar or days in a week. In plain English, "to enumerate" means to count off or name one by one from a list.

In the Java programming language, you define an enum type by using the enum keyword from java 5. Before enums we had to create an enumerated type by enclosing many final static int/String variables inside a class.

Consider an example for a traditional enumerated type identifying weeks:

Class Weekday
{
    final static int SUNDAY=0;
    final static int MONDAY=1;
    //Tuesday to Friday omitted here
    final static int SATURDAY=6;
}

We then use these constants within the code for comparisons and all like if(weekDay == Weekday.SUNDAY){//do something} where weekDay is an integer var which may contain a number from 0 to 6 which reprecents MONDAY to SATURDAY. However weekDay may contain any other integers also like 8 or 9, as there is no restriction set by the compiler. 

Few issues with these traditional enumerated types were:

  • Lack of compile time type safety. Since the types were just constants, you could pass any constant to a method that requires a week day.
  • The int constants are not descriptive and string constants can impact performance and are difficult to handle.

 

Unlike traditional enumerated types ( used in java before java 5 ) which were a set of int/String constants, enums in java, introduced in java 5, are actually classes and each constant in an enum is a public static final field that represents an instance of its enum class. You can declare enum constants seperated by commas and then end the declarations with a semicolon. After the semicolon you can have any members you can write in a normal class like fields, constructors etc. In case of constructors, you invoke them while declaring the enum constant as CONSTANT(data).

Consider an example for an enum in java:

enum Weekend {
        SATURDAY, SUNDAY
}

Here, for compiler, Weekend is actually a class and SATURDAY and SUNDAY are instances of the class Weekend. Behind the scenes, the compiler converts enum Weekend {---------} into a class with name Weekend and extends Enum<Weekend>.

It is similar to:

Class Weekend extends Enum<Weekend>{

public static final Weekend SATURDAY=new Weekend();

public static final Weekend SUNDAY=new Weekend();

}

However compiler won’t allow us to explicitly extend the Enum class.

We can add fields, constructors and methods to an enum.

Consider a modification to our previous example:

enum Weekend {       

SATURDAY("It is sat"), SUNDAY;

String name;

Weekend(String s){name=s;}

}

Here we are calling parameterized constructor for SATURDAY and calling the default one for SUNDAY. However compilation will fail as there is no default constructor because compiler will create a default constructor only if there is no other constructors. So the correct way would be:

enum Weekend {       

SATURDAY("It is sat"), SUNDAY;

String name;

Weekend(String s){name=s;}

Weekend(){name="default"; }

}

Also note that when anything else other than constants are there (like constructors or other variables), comma separated constants should be terminated with a semicolon and then only methods or contructors or other fields should come. Otherwise semicolon is optional like the first example.

Enum can also implement interfaces.

We can even enhance an enum to assign a different behavior to each constant by introducing an abstract method into the enum and overriding this method in an anonymous subclass of the constant.

Eg:

enum Weekend {

  SATURDAY

  {

          @Override

          Public void someMethod(){}

  },

  SUNDAY{

          @Override

          Public void someMethod(){}

};

Public abstract void someMethod();

}

Anonymous sub-class (of Weekend) is created using curly braces directly after constant name or after the constructor in case of parameterized constructor. If we omit the anonymous subclass here compilation will fail as there is an unimplemented abstract nethod.

Enums are supported by the switch statement from java 5. When using enum in switch statement, the enum constants are the only allowed labels for cases.

Eg:

          enum Weekend {

                   SATURDAY, SUNDAY;

          }

          /* som code*/

          Weekend weekends= Weekend.SATURDAY;

          Switch (weekends) {

          Case SATURDAY: sysout (“Saturday”);

                   break;

          case SUNDAY: sysout (“sunday”);

                   break;

          }

 

Note: The enhanced switch only allows the name of a constant as a case label, without enum type prefix.

Summary of properties of enums

  1. We can add fields, constructors and methods to an enum.
  2. Enum can also implement interfaces.
  3. Behind the scenes, the compiler converts enum Weekend {---------} into a class with name Weekend and extends Enum<Weekend>.
  4. Compiler won’t allow us to explicitly extend the Enum class.
  5. We can enhance an enum to assign a different behavior to each constant by introducing an abstract method into the enum and overriding this method in an anonymous subclass of the constant. Anonymous class is created using curly braces after the constructor or directly after constant name in case of no-parameterized constructor.
  1. When anything else other than constants are there, comma separated constants should be terminated with a semicolon. Otherwise semicolon is optional.
  1. We can use == to compare enum constants effectively because constants are final and we cannot call an enum’s constuctors to create more constants.
  2. Enums are supported by the switch statement from java 5. When using enum in switch statement, the enum constants are the only allowed labels for cases. The enhanced switch only allows the name of a constant as a case label, without enum type prefix.

 

Advantages of enums

  1. Type safety: Enums provide compile-time type safety and prevent from comparing constants in different enums.
  2. Limits inputs: The compiler won’t allow parsing a constant of a wrong enum to a method that expects an enum type. When using enum in switch statement, the enum constants are the only allowed labels for cases. IDEs like eclipse even provide autocomplete feature for filling them. When using enum in switch statement, the enum constants are the only allowed labels for cases. IDEs like eclipse even provide auto complete feature for filling them.
  3. Enums groups things in a set.
  4. Enums are iterable.

 

Use cases of enums

  1. Enumeration can be used as a singleton in java. A single element enum type is considered as the best way to implement a singleton by many.
  2. Enumerations can also be used:
    1. In place of String constants
    2. In place of integers used as types

 

Enum Methods

Object’s methods overridden by enums are:

  1. clone () – to prevent constants from being cloned.
  2. equals () – to compare constants via their references (==).
  3. finalize () – to ensure that constants cannot be finalized.
  4. hashCode () – because equals is overridden
  5. toString () – to return constant’s name.

Note: Except for toString () all are declared final so that they cannot be overridden in a subclass.

Other important methods provided by enums are:

  1. compareTo() – Enum implements Comparable.
  2. getDeclaringClass() – returns the class Object corresponding to the current constant’s enum

Eg: class cl=weekends.getDeclaringClass ();

  1. name() – returns constant’s name
  2. ordinal() – position of the constant within enum type. compareTo () compares ordinals.
  3. public static <T extends Enum <T>> T valueOf (class <T> enumType, String name) – for returning enum constant from the specified enum with the specified name.

The values() method is not actually part of Enum’s java documentation, but compiler adds this method while generating the class. The values() method of the enum returns an array of all constants that are declared in the enum.

Eg:

For (Weekend w: weekends.values())

{

  System.out.print(w.toString()+” “);

}

The default toString() method of an enum returns a constant’s name.

O/P will be : SATURDAY SUNDAY

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!

Quick Notes Finder Tags

Activities (1) advance java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (52) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exceptions (4) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (4) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (4) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (4) Java Programmer 2 (2) Javascript Frameworks (1) Java SE Professional (1) JSP (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quizzes (17) references (2) resources (1) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Sorting (1) source code management (1) spring (4) spring boot (1) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)