Java Tutorials
Java Methods
Java Classes
Java File Handling
A special enum
"category" representing a group of constants (a fixed variable, such as a final
variable).
To create an enum
, use the enum
keyword (instead of a class or visual link), and break constants with commas. Note that it must be capitalized:
enum Level {
LOW,
MEDIUM,
HIGH
}
You can access enum
constants with the dot syntax:
Level myVar = Level.MEDIUM;
The word Enum is short for "statistics", meaning "directly listed".
You can also have enum
within the class:
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:
MEDIUM
Enums are commonly used in switch
statements to check the corresponding values:
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 level
The enum type has a values()
method, which returns a list of all enum constants. This method is useful if you want to connect to enum constants:
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
The output will be:
LOW
MEDIUM
HIGH
Enum
can, as a class
, have signs and patterns. The only difference is that the enum constants are public
, static
and final
(unchangeable - they cannot be removed).
Enum
cannot be used to create objects, nor can it expand other classes (but can also use communication).
Use enums if you have numbers that you know will not change, such as days of the month, days, colors, deck of cards, etc.