The Wayback Machine - https://web.archive.org/web/20240910090716/https://www.geeksforgeeks.org/enum-in-java/
Open In App

enum in Java

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java,Enumerations or Java Enum serve the purpose of representing a group of named constants in a programming language. Java Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc.

What is Enumeration or Enum in Java?

A Java enumeration is a class type. Although we don’t need to instantiate an enum using new, it has the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just like classes, you can give them constructors, add instance variables and methods, and even implement interfaces.

Enum Example:

The 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). 

One thing to keep in mind is that, unlike classes, enumerations neither inherit other classes nor can get extended(i.e become superclass).  We can also add variables, methods, and constructors to it. The main objective of an enum is to define our own data types(Enumerated Data Types).

Declaration of enum in Java

Enum declaration can be done outside a class or inside a class but not inside a method.

1. Declaration outside the class

Java
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color {
    RED,
    GREEN,
    BLUE;
}

public class Test {
    // Driver method
    public static void main(String[] args) {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

Output
RED

2. Declaration inside a class

Java
// enum declaration inside a class.
public class Test {
    enum Color {
        RED,
        GREEN,
        BLUE;
    }

    // Driver method
    public static void main(String[] args) {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

Output
RED
  • The first line inside the enum should be a list of constants and then other things like methods, variables, and constructors.
  • According to Java naming conventions, it is recommended that we name constant with all capital letters

Properties of Enum in Java

There are certain properties followed by Enum as mentioned below:

  • Class Type: Every enum is internally implemented using the Class type.
  • Enum Constants: Each enum constant represents an object of type enum.
  • Switch Statements: Enum types can be used in switch statements.
  • Implicit Modifiers: Every enum constant is implicitly public static final. Since it is static, it can be accessed using the enum name. Since it is final, enums cannot be extended.
  • Main Method: Enums can declare a main() method, allowing direct invocation from the command line.

Below is the implementation of the above properties:

Java
// A Java program to demonstrate working on enum
// in a switch case (Filename Test.java)

import java.util.Scanner;

// An Enum class
enum Day {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY;
}

// Driver class that contains an object of "day" and
// main().
public class Test {
    Day day;

    // Constructor
    public Test(Day day) {
        this.day = day;
    }

    // Prints a line about Day using switch
    public void dayIsLike() {
        switch (day) {
        case MONDAY:
            System.out.println("Mondays are bad.");
            break;
        case FRIDAY:
            System.out.println("Fridays are better.");
            break;
        case SATURDAY:
        case SUNDAY:
            System.out.println("Weekends are best.");
            break;
        default:
            System.out.println("Midweek days are so-so.");
            break;
        }
    }

    // Driver method
    public static void main(String[] args) {
        String str = "MONDAY";
        Test t1 = new Test(Day.valueOf(str));
        t1.dayIsLike();
    }
}

Output
Mondays are bad.

Java Enum Programs

1. Main Function Inside Enum

Enums can have a main function, allowing them to be invoked directly from the command line.

Below is the implementation of the above property:

Java
// A Java program to demonstrate that we can have
// main() inside enum class.

public enum Color {
    RED,
    GREEN,
    BLUE;

    // Driver method
    public static void main(String[] args) {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

Output
RED

The above program will not run on online compiler. To run this program, save it as Color.java and use the java command to compile and execute.

2. Loop through Enum

We can iterate over the Enum using the values() method, which returns an array of enum constants.

Below is the implementation of the loop through Enum:

Java
// Java Program to Print all the values
// inside the enum using for loop
import java.io.*;

// Enum Declared
enum Color {
    RED,
    GREEN,
    BLUE;
}

// Driver Class
class GFG {

    // Main Function
    public static void main(String[] args) {
        // Iterating over all the values in
        // enum using for loop
        for (Color var_1 : Color.values()) {
            System.out.println(var_1);
        }
    }
}

Output
RED
GREEN
BLUE

3. Enum in a Switch Statement

Enums can be used in switch statements to handle different cases based on the enum constants.

Java
// Java Program to implement
// Enum in a Switch Statement
import java.io.*;

// Driver Class
class GFG {
    // Enum Declared
    enum Color {
        RED,
        GREEN,
        BLUE,
        YELLOW;
    }

    // Main Function
    public static void main(String[] args) {
        Color var_1 = Color.YELLOW;

        // Switch case with Enum
        switch (var_1) {
        case RED:
            System.out.println("Red color observed");
            break;
        case GREEN:
            System.out.println("Green color observed");
            break;
        case BLUE:
            System.out.println("Blue color observed");
            break;
        default:
            System.out.println("Other color observed");
        }
    }
}

Output
Other color observed

Enum and Inheritance

  • All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, an enum cannot extend anything else.
  • toString() method is overridden in java.lang.Enum class, which returns enum constant name.
  • enum can implement many interfaces.

Enum and Constructor

  • Enums can contain constructors, which are called separately for each enum constant at the time of enum class loading.
  • We can’t create enum objects explicitly and hence we can’t invoke the enum constructor directly.

Enum and Methods

Enums can have both concrete and abstract methods. If an enum class has an abstract method, each enum constant must implement it.

Java
// Java program to demonstrate that enums can have
// constructor and concrete methods.

// An enum (Note enum keyword in place of class keyword)
enum Color {
    RED,
    GREEN,
    BLUE;

    // Enum constructor called separately for each
    // constant
    private Color() {
        System.out.println("Constructor called for : " + this.toString());
    }

    public void colorInfo() {
        System.out.println("Universal Color");
    }
}

public class Test {
    // Driver method
    public static void main(String[] args) {
        Color c1 = Color.RED;
        System.out.println(c1);
        c1.colorInfo();
    }
}

Output
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Note: While the set of constants in a Java enum is fixed at runtime and cannot be changed dynamically, you can modify the source code of the enum to add or remove constants and then recompile the application to reflect these changes.

Creating a Class with Enum Member

When combined with classes, enum can serve as powerful tool for organising program.

Java
/*package whatever //do not write package name here */

import java.io.*;

enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

public class EnumTest {
    // Enum member variable
    Day day;

    // constructor which takes enum value
    public EnumTest(Day day) { this.day = day; }

    // method to execute action as per enum value
    public void tellItLikeItIs()
    {
        switch (day) {
        case MONDAY:
            System.out.println("Mondays are tough");
            break;
        case TUESDAY:
            System.out.println("Tuesday are better");
            break;
        case WEDNESDAY:
            System.out.println("Wednesday are okay");
            break;
        case THURSDAY:
            System.out.println("Thursdays are hopeful");
            break;
        case FRIDAY:
            System.out.println("Fridays are exciting");
            break;
        case SATURDAY:
            System.out.println("Saturdays are relaxing");
            break;
        case SUNDAY:
            System.out.println("Sunday are for rest");
            break;
        default:
            System.out.println("Everyday are good");
            break;
        }
    }

    public static void main(String[] args)
    {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();

        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();

        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();

        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();

        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}

Output
Mondays are tough
Wednesday are okay
Fridays are exciting
Saturdays are relaxing
Sunday are for rest

The EnumTest class in above code is created with member of type Day. It has constructor which takes Day enum as an argument and assigns it.

The class has method tellItLikeItIs(), which prints message based on value of day.

The main method includes objects of EnumTest using different Day enum values and calling tellItLikeItIs() method on each.

NOTE: In the main method new is used when creating instances of EnumTest because EnumTest is a regular Java class not enum itself. So, the new keyword is used to create new instance of EnumTest class, and passing enum value to its constructor.

FAQs on Enum in Java

Can we create the instance of Enum by the new keyword?

No, we can’t create the instance of the Enum keyword because it contains private constructors only.

Can we have an abstract method in the Enum?

Yes, we have an abstract method in Enum.

What is the purpose of the values() method in the enum?

In Java, the values( ) method can be used to return all values present inside the enum.

What is the purpose of the valueOf() method in the enum?

The valueOf() method returns the enum constant of the specified string value if exists.

What is the purpose of the ordinal() method in the enum?

By using the ordinal() method, each enum constant index can be found, just like an array index.

Write a program in Java to describe the use of values(), valueOf(), and ordinal() methods in the enum.

Java
// Java program to demonstrate working of values(),
// ordinal() and valueOf()

enum Color {
    RED,
    GREEN,
    BLUE;
}

public class Test {
    public static void main(String[] args)
    {
        // Calling values()
        Color arr[] = Color.values();

        // enum with loop
        for (Color col : arr) {
            // Calling ordinal() to find index
            // of color.
            System.out.println(col + " at index "
                               + col.ordinal());
        }

        // Using valueOf(). Returns an object of
        // Color with given constant.
        // Uncommenting second line causes exception
        // IllegalArgumentException
        System.out.println(Color.valueOf("RED"));
        // System.out.println(Color.valueOf("WHITE"));
    }
}

Output
RED at index 0
GREEN at index 1
BLUE at index 2
RED

Next Article on enum: Enum with Customized Value in Java

 



Previous Article
Next Article

Similar Reads

Java.lang.Enum Class in Java
Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java Class Declaration public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable As we can see, that Enum is an abstract class, so we can not create obje
8 min read
Comparing enum members in Java
Prerequisite : enum in Java, == vs equals In Java, enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods etc. enum can be defined as a group of named constant. There are two ways for making comparison of enum members : By using ==
3 min read
Iterating over Enum Values in Java
Enum in Java is a data type that contains a fixed set of constants. A Java enum type is a special kind of Java class. An enum can contain constants, methods, etc. Given below is a demonstration of how to declare an enum: Java Code // Demonstrates the declaration of enum public enum season { Spring, Summer, Monsoon, Autumn, Winter } Iterate over Enu
3 min read
How to implement an Interface using an Enum in Java
Enumerations serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. We have already discussed the basics of enum, how its declared in the previous article. In th
3 min read
Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Why Enum Class Can Have a Private Constructor Only in Java?
Every enum constant is static. If we want to represent a group named constant, then we should go for Enum. Hence we can access it by using enum Name. Enum without a constructor: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } Enum with a constructor: enum Size { SMALL("The size is small."), MEDIUM("The size is medium."),
2 min read
Difference Between ordinal() and compareTo() in Java Enum
Enumerations serve the purpose of representing a group of named constants in a programming language. If we want to represent a group named constant then we should go for Enum. Every enum constant is static. Hence, we can access it by using enum Name. Example: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }ordinal() Metho
3 min read
Advantages and Disadvantages of using Enum as Singleton in Java
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards. Advantages of using Enum as Singlet
3 min read
Enum with Customized Value in Java
Prerequisite : enum in Java By default enums have their own string values, we can also assign some custom values to enums. Consider below example for that. Examples: enum Fruits { APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”); } In above example we can see that the Fruits enum have three members i.e APPLE, BANANA and GRAPES with have their own di
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.math.BigInteger.modInverse() method in Java
Prerequisite : BigInteger Basics The modInverse() method returns modular multiplicative inverse of this, mod m. This method throws an ArithmeticException if m <= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1). Syntax: public BigInteger modInverse(BigInteger m) Parameters: m - the modulus. Return Value: This method return
2 min read
Article Tags :
Practice Tags :