JAVA Enum

In this tutorial, we will learn about java enum. Enum in java stands for enumeration. Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named values separated by commas. These named values are also known as elements or enumerators or enum instances. Since the values in the enum type are constant, you should always represent them in UPPERCASE letters. So basically we get through “what is enum in java ?” so lets go deep into enum java.

You can use an Enum type when you need a fixed set of pre-defined constant values that are known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.

Java enum is a class in java that has a group of variables that cannot be changed. We can also call them constants or final variables. To create an enum, we use the enum keyword. It is used for things which are fixed such as days of the week – Monday, Tuesday, and Wednesday etc. Or the direction – East, West, North and South. Or the colors such as green, blue, red, yellow etc.

Java enum constants are static and final with a fixed set of constants. In Java, the pro of defining an enum is that we can create inside of the class as well as outside depending on our wish. But this cannot be done in other languages. Moreover, an enum cannot create its own class but it can extend other classes. It can also implement other interfaces just as java enum inherits enum class, but cannot extend any class. Java enum can also be used in switch statements. We use an enum to represent numeric or textual data which gives us a small set of possible value as output. Enum implements serializable interfaces in java, hence it is also possible to override enum.

As we know java ensures type safety which means we cannot perform an operation in java unless it is fully valid for the object. Java enum ensures type safety as well.

In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:

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

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile timeβ€”for example, the choices on a menu, command line flags, and so on.

Java enum Example

Example 1 :

enum direction { 
    EAST, WEST, NORTH; 
} 
public class Test 
{
    public static void main(String[] args) { 
        direction d = direction.EAST; 
        System.out.println(d); 
    } 
}


Output :

EAST

Inside the program, the first thing should be a list of final variables and then could be constructor or methods etc.

Example 2:

public class EnumTest {
    Day day;
    
    public EnumTest(Day day) {
        this.day = day;
    }
    
    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;
                    
            case TUESDAY: case WEDNESDAY: case THURSDAY:
                System.out.println("Midweek days are so-so.");
                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("Invalid day.");
                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 bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

Now we will discuss an example to see if we can how we can use enum inside class?

Now we will discuss an example to see if we can how we can use enum inside class?

public class Enum{
enum Direction { EAST, WEST, NORTH, SOUTH; 
}
public static void main(String[] args) {
Direction d=Direction.EAST;
System.out.println(d);
}
}


The output of the above program will be:

EAST

Talking about constructors of enum type, they can only be private. As a result, it will automatically create final variables for itself which are defined at the starting of the enum block of the program. We can always invoke an enum constructor ourselves.

Need Of ENUM

Java supports two types of Data Types:

  • User-Defined Datatypes
  • Inbuilt Data Types- int, float, double, char, etc. 

Sometimes inbuilt data types are not sufficient. Let’s suppose that we have data of different data types required to be stored in a single variable. In such a situation, inbuilt data types won’t fulfill the need. That’s why there is a requirement for user-defined Data Types, and enum in Java is one of them. 

Enum & Constructor

By default, enums don’t require constructor definitions and their default values are always the string used in the declaration. Though, you can give define your own constructors to initialize the state of enum types.

Example :

public enum Direction {
    // enum fields
    EAST(0), WEST(180), NORTH(90), SOUTH(270);

    // constructor
    private Direction(final int angle) {
        this.angle = angle;
    }

    // internal state
    private int angle;

    public int getAngle() {
        return angle;
    }

    @Override
    public String toString() {
        return this.name(); // Use the name of the enum as the string representation
    }
}

public class Main {
    public static void main(String[] args) {
        Direction north = Direction.NORTH;

        System.out.println(north);               // Output: NORTH
        System.out.println(north.getAngle());     // Output: 90
        System.out.println(Direction.NORTH.getAngle()); // Output: 90
    }
}


Output :

NORTH
90
90

ENUM CONSTANTS

Enum is a special data type with which we can enable pre defined variables for a constant in java. Their initial is always capital as they are constants. The enum constants can have a value which starts from 0,1,2,3 and so on. But we have to define fields and methods further if we want to initialise a specific value to them.

Summary

  • We should always write the initial of enum final variables in Capital letter.
  • We use enum keyword for creating an enum class.
  • Enum can be traversed.
  • We can use enum in switch statements.
  • Enum constant will always represent an object or type enum.
  • Main() method can always be put inside enum.
  • We can always iterate an enum variable.
  • We cannot change the value of enum once created.
  • Enum cannot create its own class.

Leave a comment

Your email address will not be published. Required fields are marked *

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!