bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Classes
Java•Java Classes

Java Enums

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Enums?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ Level {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Loop Through an Enum
Enum in a Switch Statement
Enum inside a Class

Enums

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

To create an enum , use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters:

enum Level {
 LOW, MEDIUM, HIGH
}

Enum is short for "enumerations", which means "specifically listed".

Enum inside a Class

You can also have an enum 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);
}
}

Enum in a Switch Statement

Enums are often used in switch 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;
    }
}
}

Loop Through an Enum

The enum type has a values() 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);
}

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.

Previous

Java Anonymous Class

Next

Java Enum Constructor