JavaEnums
Enums
Anenum is a special "class" that represents a group ofconstants (unchangeable variables, likefinal variables).
To create anenum, use theenum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters:
Example
enum Level { LOW, MEDIUM, HIGH}You can accessenum constants with thedot syntax:
Enum is short for "enumerations", which means "specifically listed".
Enum inside a Class
You can also have anenum inside a class:
Example
public class Main { enum Level { LOW, MEDIUM, HIGH } public static void main(String[] args) { Level myVar = Level.MEDIUM; System.out.println(myVar); }}The output will be:
MEDIUMEnum in a Switch Statement
Enums are often used inswitch statements to check for corresponding values:
Example
enum Level { LOW, MEDIUM, HIGH}public class Main { public static void main(String[] args) { Level myVar = Level.MEDIUM; switch(myVar) { case LOW: System.out.println("Low level"); break; case MEDIUM: System.out.println("Medium level"); break; case HIGH: System.out.println("High level"); break; } }}The output will be:
Medium levelLoop Through an Enum
The enum type has avalues() method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum:
Example
for (Level myVar : Level.values()) { System.out.println(myVar);}The output will be:
LOW
MEDIUM
HIGHDifference between Enums and Classes
Anenum can, just like aclass, have attributes and methods. The only difference is that enum constants arepublic,static andfinal (unchangeable - cannot be overridden).
Anenum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Why And When To Use Enums?
Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.

