Java Enums Tutorial with Examples
1. What is Java Enum
Enum in Javais a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import.
Now we see before enum exists, what java has to do in specific situations:
WeekDayConstants.java
package org.o7planning.tutorial.beforej5;
// This class defines the constants are the days of the week.
public class WeekDayConstants {
public static final int MONDAY = 2;
public static final int TUESDAY = 3;
public static final int WEDNESDAY = 4;
public static final int THURSDAY = 5;
public static final int FRIDAY = 6;
public static final int SATURDAY = 7;
public static final int SUNDAY = 1;
}
A class with a method returns the job todo in each specific day of week. (Kind of a timetable).
Timetable.java
package org.o7planning.tutorial.beforej5;
public class Timetable {
// Returns name of Job will do
public static String getJob(int dayInWeek) {
if (dayInWeek == WeekDayConstants.SATURDAY
|| dayInWeek == WeekDayConstants.SUNDAY) {
return "Nothing";
}
return "Coding";
}
}
It is obvious that such code lines are not safe. For example, you call Timetable.getJob(int) function, but the input parameter does not belong to a defined set.
- No Type-Safety: First of all it’s not type-safe; you can pass any valid int value to dayInWeek
- No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of day e.g. when you print MONDAY it will print "2" instead of "MONDAY"
See code in Java5:
WeekDay.java
package org.o7planning.tutorial.javaenum;
public enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
Timetable.java
package org.o7planning.tutorial.javaenum;
public class Timetable {
public static String getJob(WeekDay weekDay) {
if (weekDay == WeekDay.SATURDAY || weekDay == WeekDay.SUNDAY) {
return "Nothing";
}
return "Coding";
}
}
2. Can use the == operator to compare the elements of enum
Enum is a reference object like a class, interface, but it can also use the == operation
Let see how reference objects are compared.
// To compare the reference object, generally used method equals (..)
Object obj1 = .... ;
// Comparing object with null, can use the == operator
if(obj1 == null) {
}
Object obj2 = ....;
// Not null
if (obj1 != null) {
// Comparing two objects.
if(obj1.equals(obj2)) {
}
}
With Enum, you can use the == operator to compare.
CompareEnumDemo.java
package org.o7planning.tutorial.javaenum;
public class CompareEnumDemo {
public static void main(String[] args) {
WeekDay today = WeekDay.SUNDAY;
// Use the == operator to compare two elements of Enum
if (today == WeekDay.SUNDAY) {
System.out.println("Today is Sunday");
}
}
}
3. Enum in java can be used as an argument on switch statement
Like the primitive data types (int, float, ..) Enum can be used as a parameter in the switch statement.
Let's look at an example:
Let's look at an example:
SwitchDemo.java
package org.o7planning.tutorial.javaenum;
public class SwitchDemo {
public static void main(String[] args) {
WeekDay day = WeekDay.THURSDAY;
switch (day) {
case MONDAY:
System.out.println("Working day");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Holiday");
break;
default:
System.out.println(day);
}
}
}
4. Fetch on the element of Enum
We can fetch on all elements of Enum, using the method values (). See examples:
ValuesDemo.java
package org.o7planning.tutorial.javaenum;
public class ValuesDemo {
public static void main(String[] args) {
// Get all the elements of the Enum.
WeekDay[] allDays = WeekDay.values();
for (WeekDay day : allDays) {
System.out.println("Day: " + day);
}
}
}
Results of running the example:
Day: MONDAY
Day: TUESDAY
Day: WEDNESDAY
Day: THURSDAY
Day: FRIDAY
Day: SATURDAY
Day: SUNDAY
5. Enum can have Constructor and method
An Enum can have Constructors and methods. Constructors only to initialize the object within the enum, can not call outside. We see an illustration:
Gender.java
package org.o7planning.tutorial.javaenum;
public enum Gender {
// Initialize the elements from Constructor.
// The element is always final, static
MALE("M", "Male"), FEMALE("F", "Female");
private String code;
private String text;
// Constructor of Enum internal use only
// Modifier of constructor is private
// If you do not declare private, java alway understand is private.
private Gender(String code, String text) {
this.code = code;
this.text = text;
}
// Static method return Gender by code.
public static Gender getGenderByCode(String code) {
for (Gender gender : Gender.values()) {
if (gender.code.equals(code)) {
return gender;
}
}
return null;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
GenderDemo.java
package org.o7planning.tutorial.javaenum;
public class GenderDemo {
public static void main(String[] args) {
Gender marryGender = Gender.FEMALE;
System.out.println("Code: " + marryGender.getCode());
System.out.println("Text: " + marryGender.getText());
// Gender[].
for (Gender gender : Gender.values()) {
System.out.println(gender.getText());
}
String code ="M";
Gender gender= Gender.getGenderByCode(code);
System.out.println("Gender by code: "+ gender);
}
}
Results of running the example:
Code: F
Text: Female
Male
Female
Gender by code: MALE
6. Overrides method in enum
You can override the method toString () inherited from class Object.
Currency.java
package org.o7planning.tutorial.javaenum;
public enum Currency {
VND, USD, EURO ;
@Override
public String toString() {
if (this == VND) {
return "Dong";
} else if (this == USD) {
return "Dola";
}
return super.toString();
}
public static void main(String[] args) {
Currency money = Currency.USD;
System.out.println("Money " + money);
System.out.println("Money " + money.toString());
System.out.println("VND " + Currency.VND);
System.out.println("EURO " + Currency.EURO);
}
}
Results of running the example:
Money Dola
Money Dola
VND Dong
EURO EURO
7. Abstract Method in Enum
Color.java
package org.o7planning.tutorial.javaenum;
public enum Color {
RED("red") {
@Override
public String getHexCode() {
return "#ff0000";
}
},
GREEN("green") {
@Override
public String getHexCode() {
return "#00ff00";
}
},
BLUE("blue") {
@Override
public String getHexCode() {
return "#0000ff";
}
};
private String name;
Color(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract String getHexCode();
}
Java Basic
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- Java Programming for team using Eclipse and SVN
- Java WeakReference Tutorial with Examples
- Java PhantomReference Tutorial with Examples
- Java Compression and Decompression Tutorial with Examples
- Configuring Eclipse to use the JDK instead of JRE
- Java String.format() and printf() methods
- Syntax and new features in Java 8
- Java Regular Expressions Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- JDBC Driver Libraries for different types of database in Java
- Java JDBC Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Stream Tutorial with Examples
- Java Functional Interface Tutorial with Examples
- Introduction to the Raspberry Pi
- Java Predicate Tutorial with Examples
- Abstract class and Interface in Java
- Access modifiers in Java
- Java Enums Tutorial with Examples
- Java Annotations Tutorial with Examples
- Comparing and Sorting in Java
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java BiPredicate Tutorial with Examples
- Java Consumer Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- What is needed to get started with Java?
- History of Java and the difference between Oracle JDK and OpenJDK
- Install Java on Windows
- Install Java on Ubuntu
- Install OpenJDK on Ubuntu
- Install Eclipse
- Install Eclipse on Ubuntu
- Quick Learning Java for beginners
- History of bits and bytes in computer science
- Data Types in java
- Bitwise Operations
- if else statement in java
- Switch Statement in Java
- Loops in Java
- Arrays in Java
- JDK Javadoc in CHM format
- Inheritance and polymorphism in Java
- Java Function Tutorial with Examples
- Java BiFunction Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- Java Reflection Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Socket Programming Tutorial with Examples
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java Commons IO Tutorial with Examples
- Java Commons Email Tutorial with Examples
- Java Commons Logging Tutorial with Examples
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java SoftReference Tutorial with Examples
- Java Supplier Tutorial with Examples
- Java Aspect Oriented Programming with AspectJ (AOP)
Show More
- Java Servlet/Jsp Tutorials
- Java Collections Framework Tutorials
- Java API for HTML & XML
- Java IO Tutorials
- Java Date Time Tutorials
- Spring Boot Tutorials
- Maven Tutorials
- Gradle Tutorials
- Java Web Services Tutorials
- Java SWT Tutorials
- JavaFX Tutorials
- Java Oracle ADF Tutorials
- Struts2 Framework Tutorials
- Spring Cloud Tutorials