Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Enums

Enums

An enum is a specialized “class” designed to represent a collection of constants, akin to unchangeable variables such as final variables.

To define an enum, utilize the enum keyword (as opposed to class or interface), and delineate the constants with commas. It’s essential to denote the constants in uppercase letters.

Example

enum Level {
  LOW,
  MEDIUM,
 
HIGH
}

Enum constants can be accessed using the dot syntax.

Level myVar = Level.MEDIUM
Enum is short for “enumerations”, which means “specifically listed”.

Enum inside a Class

It is also possible to include an enum within 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 would be:

MEDIUM

Enum in a Switch Statement

Enums are commonly utilized in switch statements to verify matching 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 level 

Loop Through an Enum

The enum type includes a values() method, which yields an array containing all enum constants. This method proves handy when iterating through the constants of an enum.

Example

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

The result will be:

LOW
MEDIUM
HIGH

 

Difference between Enums and Classes

An enum, akin to a class, can possess attributes and methods. The key distinction lies in the fact that enum constants are inherently public, static, and final (immutable and cannot be overridden).

Enums cannot instantiate objects, nor can they extend other classes (although they can implement interfaces).

Why And When To Use Enums?

Employ enums for values expected to remain constant, such as days of the week, colors, deck of cards, etc.