Understanding Java Enums

In Java, an enum is a special data type that represents a fixed set of constants. Enums are used to define variables that can only take predefined values, similar to final variables, ensuring a controlled set of possible values.



Java Enums

An enum in Java is a special type that represents a group of constants, which are unchangeable variables similar to final variables.

Example of Enum

To create an enum, use the enum keyword and list the constants in uppercase:

Syntax

enum Level {
LOW,
MEDIUM,
HIGH
}
Output

LOW
MEDIUM
HIGH

You can access enum constants using dot syntax, for example, Level myVar = Level.MEDIUM;.

Enum Inside a Class

An enum can also be defined inside a class:

Syntax

public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}

public static void main(String[] args) {
Level myVar = Level.MEDIUM; 
System.out.println(myVar);
}
}
Output

MEDIUM

Using Enums in Switch Statements

Enums are commonly used in switch statements to handle different constant values:

Syntax

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;
}
}
}
Output

Medium level

Loop Through an Enum

The values() method of an enum type returns an array of all enum constants, useful for looping through them:

Syntax

for (Level myVar : Level.values()) {
System.out.println(myVar);
}
Output

LOW
MEDIUM
HIGH

Differences Between Enums and Classes

An enum can have attributes and methods like a class, but its constants are public, static, and final (unchangeable). Unlike classes, enums cannot be instantiated or extended.

When to Use Enums?

Use enums when you have values that are fixed and known in advance, such as days of the week, months of the year, or categories like colors or sizes.