Examples of Java Enum
Enumeration in Java is commonly used to represent a set of predefined constants. A classic example is defining days of the week or directions. Using Enum in Java improves code clarity and eliminates the need for magic strings or numbers.
Example 1: Enum for Days of the Week
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class Main {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println("Today is: " + today);
}
}
Example 2: Enum with Fields and Methods
enum Status {
SUCCESS(200), ERROR(500);
private int code;
Status(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
public class Main {
public static void main(String[] args) {
Status status = Status.SUCCESS;
System.out.println("Status code: " + status.getCode());
}
}
These examples show how Java Enum is used in real-world scenarios to simplify logic, improve maintainability, and ensure type safety.
What is the Enum in Java?
Enum can be created using the enum keyword, just like we use the class keyword to create a class. We then write all the constants to that enum separated by commas. one more vital thing to be taken care of is that all the constants should be in uppercase letters.
Syntax
Let’s go through the syntax for the enum-
enum enumname {CONSTANT1, CONSTANT2,..... ;}
Declaration of Enum in Java
In Java, an enum (short for enumeration) is a special data type used to define a collection of constants. Enums help improve code readability and type safety when working with fixed sets of known values—like days of the week, colors, or directions.
Syntax to Declare Enum:
enum Color {
RED, GREEN, BLUE
}
Here:
- enum is the keyword.
- Color is the name of the enum.
- RED, GREEN, and BLUE are constant values of the Color enum.
Key Points:
- Enums in Java are implicitly public, static, and final.
- Each enum constant is an object of its enum type.
- You can use enums in switch statements, assign them to variables, or compare them using ==.
Example Usage:
Color myColor = Color.RED;
System.out.println("Selected color: " + myColor);
This allows cleaner, safer code compared to using raw string or int constants. Java Enum types also support fields, methods, and constructors, making them powerful and flexible.
Need for Enum in Java
The first thought that might come to your mind is if we have to store a fixed set of constants, why can’t we use arrays or linked lists for this. The answer is because they are mutable, i.e., the values stored in them might be changed at some point in the program, but in the case of enum, i.e., the fixed set of constants, the value of these constants should never change.
Also, Java enums can have constructors and methods just like other classes, increasing its functionality. It also has some other significant advantages like improved type safety, ease of using it in switch cases, and it can also be used for traversal.
Java Enums and Classes
Though java enums are said to be classes with a fixed set of constants, they are not like any other class in Java, so let’s have a look at a comparison of them with an ordinary Java class for different properties-
- Overriding constants- constants are fixed in java enums, i.e., they can’t be overridden. In contrast, a regular java class can be easily overridden.
- Creation of objects- the creation of objects is not supported in java enums. Also, we can’t call the constructor directly. In contrast, the regular java classes support the creation of objects.
- Extending other classes- we can’t use java enum to extend other classes. Whereas in the case of regular java classes, one class can extend other classes.
- Implementing the interface- we can use both the enums and classes to implement the interfaces.
Let’s learn the examples where using java enums makes the code easy to handle and efficient. Also, we will see some of the important methods associated with it-
Switch Cases using Java Enums
we can use java enums for switch statements, as the numbers of the constants are already known. Though the switch statement cases must use the constants of the same enum used by the switch statement. Let’s have a look at an example to see how it’s implemented-
import java.util.Scanner;
//Creating an enum class.
enum Cards
{
HEART, DIAMOND, CLUB, SPADE;
}
//Driver class.
public class demo
{
Cards cards;
// Constructor for the demo class.
public demo(Cards cards)
{
this.cards=cards;
}
//Using switch to display the picked card.
public void pickedcard()
{
switch(cards)
{
case HEART:
System.out.println("We got a HEART.");
break;
case DIAMOND:
System.out.println("We got a DIAMOND.");
break;
case CLUB:
System.out.println("We got a CLUB.");
break;
case SPADE:
System.out.println("We got a SPADE.");
break;
}
}
//Driver method.
public static void main(String[] args)
{
//Using standard input stream.
Scanner sc= new Scanner(System.in);
System.out.print("Enter the drawn card: ");
//Taking the input string.
String s= sc.nextLine();
demo Draw= new demo(Cards.valueOf(s));
Draw.pickedcard();
}
}
Input
Enter the drawn card:
HEART
Output
We got a HEART.
Use Cases of Java Enums
- Inheritance using java enums- Java enums extend Java.lang. Enum class by default, and since Java only permits the extension of one parent class, it can not extend any other class. The Java.lang. Enum class overrides the tostring() method. This method returns the enum constant name. Also, we can implement interfaces using java enums.
- Customizing enum values- java Enum allows us to modify the default string values assigned to the constant.
- Enums in if else if statement- We use a Java enum to implement if else if statements.
Must Read Type Conversion in Java
Methods Used with Java Enums
We can use methods like values(), ordinal(), and valueof() with the java enum(). These are by default added into the Java enum class.
- Values()- this method returns an array of all the values held by the constants in the enum.
public static enum-name[ ] values()
- Valueof()- this method is used to get the constant whose value is passed as an argument while calling this method.
public static enum-name valueOf (String s)
- Ordinal()- this method does the opposite of valueof() method. i.e., we pass the constant to it, and it returns the value of that constant in the enum.
public final int ordinal()
Let’s see an example in which we have used all three methods.
import java.util.Scanner;
//Creating the enum named Days.
enum Days
{
MON, TUE, WED, THU, FRI, SAT, SUN;
}
//Creating the demo class
public class Demo
{
public static void main(String[] args)
{
//Using values() method.
Days array[] = Days.values();
//Using enum for traversing in a loop.
for (Days ds : array)
{
//Using the Ordinal() method..
System.out.println(ds + "'s position " + ds.ordinal());
}
//Using try and catch to check the working of valueOf()
//method, so that if the passed string is present, it will
//return the constant, or throw an error.
try
{
//Using standard input stream.
Scanner sc= new Scanner(System.in);
System.out.print("Enter the string ");
//Taking the input string.
String s= sc.nextLine();
//Using valueOf() method.
System.out.println(Days.valueOf(s));
}
catch(Exception e)
{
System.out.println("Absent");
}
}
}
Input
Enter the string
MON
Output
MON's position 0
TUE's position 1
WED's position 2
THU's position 3
FRI's position 4
SAT's position 5
SUN's position 6
MON
Properties of Java Enum
Below are the key properties of the Enum in Java:
- Fixed Set of Constants
Java Enum defines a set of named constants that cannot be changed once declared.
- Type-Safe
Enums are strongly typed, meaning you can’t assign any value other than the predefined constants.
- Can Have Fields, Methods, and Constructors
Unlike in many other languages, Java Enums can include variables, methods, and constructors for added functionality.
- Implicitly Final and Static
Enum constants are automatically static and final, meaning they are class-level and unchangeable.
- Can Be Used in Switch Statements
You can use enum values directly in switch statements, improving readability.
- Implements java.lang.Enum Internally
All enums implicitly extend java.lang.Enum, so they cannot extend any other class.
- Supports Iteration
You can iterate over all enum values using the values() method.
- Can Implement Interfaces
Enums in Java can implement interfaces to define custom behavior.
- No Need for New Keyword
You don’t need to use the new keyword to create enum objects; they’re created automatically.
These properties make Java Enum a powerful feature for handling constant values in a structured and readable way.
Frequently Asked Questions
Can enum have methods in Java?
Yes, Java enums can have methods. For example there are methods like values(), valueOf(), ordinal(), etc.
Is Java enum an object?
No, Java enum is a class with a fixed set of constants. It can have constructors, methods as well.
What is the enumerate method in Java?
Java does not have a built-in enumerate method like Python. Instead, you use Enumeration or enhanced for-loops to iterate over elements in legacy collections.
When to use enum in Java?
Use enum in Java when you need a fixed set of constants like days, directions, or states to ensure type safety, readability, and controlled values.
How is enum serialized in Java?
Serialization of java enums is different from regular serialization of objects. Java enums are serialized by solely using their name; field values of constants are not used.
Conclusion
In this blog, we learned about Enumeration in Java, its declaration, and usage. We explored how Java Enum provides a type-safe way to define constant values. It simplifies code, especially in switch statements, and improves readability and maintainability. We also covered useful enum in Java methods like values() and valueOf(), which enhance flexibility. Enums are a powerful feature that every Java developer should leverage for cleaner and more efficient code.
Recommended Readings: