Java Enum Fundamentals

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn about enums in Java. Enums are a special data type in Java that allows us to define a fixed set of constants. You will learn how to create, use, and manipulate enums in Java.

Creating an Enum

  1. Create a new file with the name StudentResult.java in the ~/project directory.
  2. Add the following code to create an enum named StudentResult:
public enum StudentResult {
    PASS,
    FAIL,
    ABSENT
}

Using Enums

  1. Create a new file with the name Demo.java in the ~/project directory.
  2. Add the following code to create a variable of the StudentResult enum type and use its values:
public class Demo {
    public static void main(String[] args) {
        StudentResult result1 = StudentResult.ABSENT;
        StudentResult result2 = StudentResult.FAIL;
        StudentResult result3 = StudentResult.PASS;

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
    }
}
  1. Run the code using the following command in the terminal:
javac Demo.java && java Demo

Using Enums with If-Else Statements

  1. Add the following code to use the StudentResult enum with if-else statements:
public class Demo {
    public static void main(String[] args) {
        StudentResult result = StudentResult.FAIL;

        if(result == StudentResult.ABSENT)
            System.out.println("The student was absent for the exam.");

        else if(result == StudentResult.PASS)
            System.out.println("The student passed the exam.");

        else if(result == StudentResult.FAIL)
            System.out.println("The student failed the exam.");
    }
}

Using Enums with Switch Statements

  1. Add the following code to use the StudentResult enum with switch statements:
public class Demo {
    public static void main(String[] args) {
        StudentResult result = StudentResult.FAIL;

        switch(result) {
            case ABSENT : System.out.println("The Student was absent for the exam.");
            break;

            case PASS : System.out.println("The Student passed the exam.");
            break;

            case FAIL : System.out.println("The Student failed the exam.");
            break;
        }
    }
}

Iterating Over Enums

  1. Add the following code to iterate over the StudentResult enum:
public class Demo {
    public static void main(String[] args) {
        StudentResult[] resultArr = StudentResult.values();

        for(StudentResult sr : resultArr) {
            System.out.println(sr + " at index " + sr.ordinal());
        }
    }
}

Using the toString() Method of Enums

  1. Add the following code to use the toString() method of enums:
public class Demo {
    public static void main(String[] args) {
        for(StudentResult sr : StudentResult.values()) {
            String resultStr = sr.toString();
            System.out.println("Uppercase: " + resultStr);
            System.out.println("Lowercase: " + resultStr.toLowerCase());
            System.out.println();
        }
    }
}

Creating Enums From Strings

  1. Add the following code to create enums from strings:
public class Demo {
    public static void main(String[] args) {
        String resultStr = "FAIL";
        StudentResult result = StudentResult.valueOf(resultStr);
        System.out.print("Enum from String: " + result);
    }
}
  1. Run the code using the following command in the terminal:
javac Demo.java && java Demo

Creating Enums Inside Classes

  1. Add the following code to create an enum inside a class and use it:
public class Student {
    String name;
    StudentResult result;

    // Defining an enum type
    enum StudentResult {
        PASS,
        FAIL,
        ABSENT;
    }

    // Constructor
    Student(String s, StudentResult sr) {
        name = s;
        result = sr;
    }

    // Enum if-else method
    public void printResult() {
        if (this.result == StudentResult.ABSENT)
            System.out.println(this.name + " was absent for the exam.");

        else if (this.result == StudentResult.PASS)
            System.out.println(this.name + " passed the exam.");

        else
            System.out.println(this.name + " failed the exam.");
    }

    // Enum method
    public boolean wasAbsent() {
        if (this.result == StudentResult.ABSENT)
            return true;
        else
            return false;
    }

    // Main method
    public static void main(String[] args) {
        Student s1 = new Student("Justin", StudentResult.ABSENT);
        Student s2 = new Student("Jessica", StudentResult.PASS);

        s1.printResult();
        s2.printResult();

        System.out.println("Student s1 was absent: " + s1.wasAbsent());
    }
}
  1. Run the code using the following command in the terminal:
javac Student.java && javac Demo.java && java Student

Using EnumSet

  1. Add the following code to use EnumSet:
import java.util.EnumSet;

enum StudentResult {
    PASS,
    FAIL,
    ABSENT;
}

public class Demo {
    public static void main(String[] args) {
        EnumSet<StudentResult> resultSet1 = EnumSet.of(StudentResult.FAIL, StudentResult.PASS);
        EnumSet<StudentResult> resultSet2 = EnumSet.allOf(StudentResult.class);

        System.out.println("Enum Set-1: " + resultSet1);
        System.out.print("Enum Set-2: " + resultSet2);
    }
}

Using EnumMaps

  1. Add the following code to use EnumMaps:
import java.util.EnumMap;
import java.util.Map;

enum StudentResult {
    PASS,
    FAIL,
    ABSENT;
}

public class Demo {
    public static void main(String[] args) {
        EnumMap<StudentResult, String> resultMap = new EnumMap<>(StudentResult.class);
        resultMap.put(StudentResult.PASS, "Student Passed the exam");
        resultMap.put(StudentResult.FAIL, "Student Failed the exam");
        resultMap.put(StudentResult.ABSENT, "Student was absent for the exam");

        for (Map.Entry<StudentResult, String> e : resultMap.entrySet())
            System.out.println(e.getKey() + " --> " + e.getValue());
    }
}

Summary

In this lab, you learned how to create an enum, use it with if-else and switch statements, iterate over an enum, use its toString() method, create enums from strings, create an enum inside a class, use EnumSet to efficiently store enum constants, use EnumMaps for storing key-value pairs of enums, and use concrete and abstract methods in enums. You also learned that enums are used to define a collection of constant values and that they increase type safety in Java.

Other Java Tutorials you may like