Java Tutorial · Object-Oriented Java · Lesson 23 of 37
Java Enums
Define a fixed set of constants with fields, methods and switch support.
Basic enums
An enum is a type with a fixed set of named constants:
public class Main {
public static void main(String[] args) {
Level level = Level.MEDIUM;
System.out.println(level + " " + level.ordinal());
switch (level) {
case LOW -> System.out.println("Relax");
case MEDIUM -> System.out.println("Pay attention");
case HIGH -> System.out.println("Act now");
}
for (Level l : Level.values()) System.out.print(l + " ");
System.out.println();
System.out.println(Level.valueOf("HIGH") == Level.HIGH);
}
enum Level { LOW, MEDIUM, HIGH }
}
Output
MEDIUM 1 Pay attention LOW MEDIUM HIGH true
Run this on your computer — see “Get Started” for setup.
Enums with fields and methods
Enum constants are objects, so they can have constructors, fields and methods:
public class Main {
public static void main(String[] args) {
for (Planet p : Planet.values()) {
System.out.printf("%-7s weight of 70kg person: %.1f kg%n", p, p.weightOf(70));
}
}
enum Planet {
MERCURY(0.38), EARTH(1.0), JUPITER(2.53);
private final double gravity;
Planet(double gravity) {
this.gravity = gravity;
}
double weightOf(double earthKg) {
return earthKg * gravity;
}
}
}
Output
MERCURY weight of 70kg person: 26.6 kg EARTH weight of 70kg person: 70.0 kg JUPITER weight of 70kg person: 177.1 kg
Run this on your computer — see “Get Started” for setup.
EnumMap and EnumSet are very fast collections keyed by enums.
Test yourself
Which method converts the string "HIGH" into the enum constant Level.HIGH?
Level.parse("HIGH")Level.valueOf("HIGH")new Level("HIGH")Level.from("HIGH")
Show answer
Answer: Level.valueOf("HIGH")