Enum is a special class that represents constants. It provides type-safe checking. For example, we could create a method that will accept only specific values and for other values, it will give a compilation error. Without enum, we would probably find out about the wrong value during the runtime. The compile time errors are always better than runtimes.
- Enum syntax
- Enum with methods and switch statement
- Advance enum
Enum syntax
public enum DayOfWeek {
MON, TUE, WED, THUR, FRI, SAT, SUN
}
- Enum is a special class for constants so to create the enum we need to write
enum
instead ofclass
. - In the body of enum, we can just list all constant values enum should have.
- As a constant, the values of enum go in uppercase.
public class Main {
public static void main(String[] args) {
DayOfWeek day = DayOfWeek.FRI;
System.out.println(day); // FRI
day = DayOfWeek.MON;
System.out.println(day); // MON
System.out.println(DayOfWeek.SUN); // SUN
}
}
- We can get enum by using its name and actual constant value.
- We can create a variable that can hold enum.
// return all values as array
DayOfWeek[] values = DayOfWeek.values();
for (DayOfWeek day : values) {
System.out.println(day);
}
DayOfWeek myDay = DayOfWeek.valueOf("MON");
// We can get enum from string using valueOf method
// It's case sensitive and value should match exactly
// otherwise exception will occur
// DayOfWeek myDay = DayOfWeek.valueOf("mon"); exception here
- The enum has few methods. In the above example, I’m showing two of them.
- values() — return all values of enum as an array
- valueOf(String) — it’s possible to get enum from a string as well.
DayOfWeek day = DayOfWeek.MON;
DayOfWeek day1 = DayOfWeek.MON;
System.out.println(day == day1); // true
System.out.println(day.equals(day1)); // true
- We can check enums on equality with
==
operator and withequals()
method.
Enum with methods and switch statement
public class Main {
public static void disStudyMsg(String day) {
switch (day) {
case "MON":
case "WED":
case "FRI":
System.out.println("Java coding day");
break;
case "TUE":
case "THUR":
System.out.println("Reading day");
break;
case "SAT":
case "SUN":
System.out.println("Getting rest day");
break;
default:
throw new IllegalArgumentException("No supported day: " + day);
}
}
public static void main(String[] args) {
disStudyMsg("MON"); // Java coding day
disStudyMsg("Sunday"); // exception here
}
}
- above method was designed without enum. The method accepts a string as a day and the method will print a message. Note, if client code will provide wrong input, the method will throw a runtime exception. It would be great to catch wrong input during the compilation stage. We can use our enum to do so.
public class Main {
public static void disStudyMsg(DayOfWeek day) {
switch (day) {
case MON:
case WED:
case FRI:
System.out.println("Java coding day");
break;
case TUE:
case THUR:
System.out.println("Reading day");
break;
case SAT:
case SUN:
System.out.println("Getting rest day");
break;
}
}
public static void main(String[] args) {
disStudyMsg(DayOfWeek.MON); // Java coding day
//disStudyMsg(DayOfWeek.Sunday); // does not compile
// there is no Sunday value in DayOfWeek enum
}
}
- When using Enum we are making sure that client code never can provide wrong input. It will not just simply compile.
- The switch statement can be used with Enum. Notice, the case value does not have an enum name but just its value.
Advance Enum
It’s always good to keep enum as a simple list of constant values. However, sometimes you might need extra features for your enum. Enum can have constructors, fields, and methods.
public enum Grade {
A("90-100"),
B("80-89"),
C("70-79"),
D("60-69"),
F("0-59");
private String gradeDescription;
private Grade(String desc) {
this.gradeDescription = desc;
}
public void seeDescription() {
System.out.println(this.gradeDescription);
}
}
- Notice, we have
;
after list of values. Without it will not compile. - Enum can have only private constructors. It can be used inside the enum only. When declaring our constant enums we need to provide value for our constructor.
public class Main {
public static void main(String[] args) {
Grade grade = Grade.A;
System.out.println(grade); // A
grade.seeDescription(); // 90-100
}
}
This is it for Enum in Java. Have a nice day!
Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming
OS, File, and File System
Working with terminal
Welcome to Java Programming Language
Variables and Primitives in Java
Convert String to numeric data type
Input from the terminal in Java
Methods with Java
Java Math Operators and special operators
Conditional branching in Java
Switch statement in Java
Ternary operator in Java
Enum in Java
String class and its methods in Java
Loops in Java
Access modifiers in Java
Static keyword in Java
The final keyword in Java
Class and Object in Java
Object-Oriented Programming in Java
OOP: Encapsulation in Java
OOP: Inheritance in Java
OOP: Abstraction in Java
OOP: Polymorphism in Java
The method Overriding vs Overloading in Java
Array in Java
Data Structures with Java
Collection framework in Java
ArrayList in Java
Set in Java
Map in Java
Date and Time in Java
Exception in Java
How to work with files in Java
Design Patterns
Generics in Java
Multithreading in java
Annotations in Java
Reflection in Java
Reflection & Annotations - The Powerful Combination
Run terminal commands from Java
Lambda in Java
Unit Testing in Java
Big O Notation for coding interviews
Top Java coding interview questions for SDET