Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active March 18, 2016 21:10
Show Gist options
  • Select an option

  • Save simonwoo/af076f263eee7879e5b6 to your computer and use it in GitHub Desktop.

Select an option

Save simonwoo/af076f263eee7879e5b6 to your computer and use it in GitHub Desktop.

Java Enum is a type like class and interface and can be used to define a set of Enum constants. Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can be used inside switch statement like int variables.

Benefits:

  • Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is a compiler error to assign something else, unlike the public static final variables used in Enum int pattern and Enum String pattern.
  • Enum has its own namespace.
  • The best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type. We will also see an example of using java enum in switch statement in this java enum tutorial.
  • Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.
public enum Currency { 
  PENNY, NICKLE, DIME, QUARTER 
}; 
Currency coin = Currency.PENNY; 
coin = 1; //compilation error 
public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

// private constructor
        private Currency(int value) {
                this.value = value;
        }
};  

Since constants defined inside Enum in Java are final you can safely compare them using "==", the equality operator

Currency usCoin = Currency.DIME; 
if(usCoin == Currency.DIME){ 
  System.out.println("enum in java can be compared using =="); 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment