Java Enums Tutorial with Examples
1. What is Java Enum
No ADS
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
No ADS
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
No ADS
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
No ADS
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();
}
No ADS
Java Basic
- Data Types in java
- Java PhantomReference Tutorial with Examples
- JDK Javadoc in CHM format
- Java Stream Tutorial with Examples
- Java Predicate Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- Arrays in Java
- JDBC Driver Libraries for different types of database in Java
- Abstract class and Interface in Java
- Java Commons Email Tutorial with Examples
- Install Eclipse
- Bitwise Operations
- Install Eclipse on Ubuntu
- Configuring Eclipse to use the JDK instead of JRE
- Java Commons Logging Tutorial with Examples
- Java Enums Tutorial with Examples
- Loops in Java
- Java Regular Expressions Tutorial with Examples
- Install Java on Ubuntu
- Quick Learning Java for beginners
- Install Java on Windows
- Comparing and Sorting in Java
- Inheritance and polymorphism in Java
- Java Consumer Tutorial with Examples
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- if else statement in java
- Switch Statement in Java
- Java Supplier Tutorial with Examples
- Java Programming for team using Eclipse and SVN
- Java JDBC Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- What is needed to get started with Java?
- Java Aspect Oriented Programming with AspectJ (AOP)
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java Compression and Decompression Tutorial with Examples
- Java Reflection Tutorial with Examples
- Install OpenJDK on Ubuntu
- Java String.format() and printf() methods
- History of Java and the difference between Oracle JDK and OpenJDK
- Introduction to the Raspberry Pi
- Java Socket Programming Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java WeakReference Tutorial with Examples
- Java Commons IO Tutorial with Examples
- History of bits and bytes in computer science
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java SoftReference Tutorial with Examples
- Syntax and new features in Java 8
- Java Annotations Tutorial with Examples
- Java Function Tutorial with Examples
- Access modifiers in Java
- Java BiFunction Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Functional Interface Tutorial with Examples
- Java BiPredicate Tutorial with Examples
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