top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Enum in Java

Introduction

If you are a programming enthusiast who wants to learn more about Enum in Java, you have come to the right place. Enum in Java is a special type of data or constant. It is an integral part of Java, introduced first in Java 5. 

Overview

The following tutorial deals with questions such as what is Enumeration in Java, examples of Enumeration in Java, abstract methods in Enum, and a lot more. Read on to master Enumeration in Java!

What is Enumeration in Java? 

Enumeration in Java is a data type that defines a set of named constants. It is used to create a list of values assigned to a type. This can then be used in the program.

In Java, Enumerations are represented using the "enum" keyword. 

Here is an example of how to create an Enumeration:

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

In this example, the "Days" Enumeration contains seven named constants: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY. We can use these constants in the program to represent the days of the week.

Enumerations are helpful because they allow you to define a set of values that are meaningful in the context of your program. They also help prevent errors by ensuring only valid values are used. We can also use Enumerations to switch statements. This makes it easy to write code that handles different cases based on the value of an Enumeration.

Why Do We Need Enumeration? 

Enumerations are helpful in programming for several reasons. Here are some of them:

Readability and Maintainability: Enumerations can increase the readability of a code. They can also make it easier to understand. Instead of using integer or string constants that are unclear or not memorable, using named constants that are meaningful in the program's context can help improve a code's readability. Moreover, if changes need to be made to the set of constants, it is much easier to do so with an Enumeration.

Type Safety: Type safety assists in preventing programming errors. For instance, if a method requires an Enumeration value as an argument, it cannot be accidentally passed an invalid value.

Compile-Time Checking: The Java compiler verifies that Enumeration values are used correctly. These checks could include ensuring that each value in the Enumeration is declared only once. It also verifies that the values are of the proper type. This can aid in detecting faults before they cause difficulties during runtime.

Switch Statements: Enumerations can be used in switch statements to make code shorter and easier to read. Instead of utilizing a sequence of if-else statements, a switch statement can be used to conduct different actions based on the value of an Enumeration.

Simple Example of Java Enum 

Here is a simple Enum example in Java:

public enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class Main {
    public static void main(String[] args) {
        DayOfWeek today = DayOfWeek.WEDNESDAY;
        System.out.println("Today is " + today);
    }
}

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

The “values()” method is a built-in method in Java Enum. This returns an array of all the values defined in the Enumeration.

The “values()” method provides an easy way to access all the values defined in the Enumeration. This is done without manually creating an array of all the values.

Here is an example of Enum with “values()” in Java:
public enum Month {
    JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
    JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}
public class ExampleEnum {
    public static void main(String[] args) {
        Month[] months = Month.values();
        for (Month month : months) {
            System.out.println(month);
        }
    }
}

What is The Purpose of The “valueOf() method” in The Enum?

The “valueOf()” method is a built-in method in Java Enum. This returns the Enum constant of the specified string value. 

The “valueOf()” method provides a convenient way to convert a string value into an Enum constant. This can be useful in many cases. For instance, when reading input from a user or a file, we need to convert a string value into an Enum constant.

Here is an example of how to use the “valueOf()” method in Java Enum with string values:

public enum Color {
    RED, GREEN, BLUE
}
public class ExampleEnum {
    public static void main(String[] args) {
        String colorString = "GREEN";
        Color color = Color.valueOf(colorString);
        System.out.println("The color is " + color);
    }
}

What is The Purpose of The “ordinal() method” in The Enum?

The “ordinal()” method is a built-in method in Java Enum. This returns the ordinal value of an Enum constant. The ordinal value is an integer that represents the position of the Enum constant in the Enumeration, starting from zero.

The purpose of the “ordinal()” method is to provide a convenient way to get the position of an Enum constant in the Enumeration. This can be useful in many cases. For instance, we need to perform comparisons or sorting operations on Enum constants based on their position in the Enumeration.

Here is an example of how to use the “ordinal()” method:

public enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}
public class ExampleEnum {
    public static void main(String[] args) {
        Weekday day = Weekday.WEDNESDAY;
        int ordinal = day.ordinal();
        System.out.println("The ordinal value of " + day + " is " + ordinal);
    }
}

Initializing Specific Values to The Enum Constants

You can initialize specific values to the Enum constants. This can be done using a constructor. Here is an example:

public enum Color {
    RED(255, 0, 0),
    GREEN(0, 255, 0),
    BLUE(0, 0, 255);
    private int r;
    private int g;
    private int b;
    private Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }
    public int getRed() {
        return r;
    }
    public int getGreen() {
        return g;
    }
    public int getBlue() {
        return b;
    }
}
public class ExampleEnum {
    public static void main(String[] args) {
        Color color = Color.GREEN;
        System.out.println("The color is " + color);
        System.out.println("The RGB values are " + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue());
    }
}

Example of Specifying Initial Value to The Enum Constants

Here is an example of how to specify an initial value to the Enum constants:

public enum Size {
    SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
    private final String abbreviation;
    private Size(String abbreviation) {
        this.abbreviation = abbreviation;
    }
    public String getAbbreviation() {
        return abbreviation;
    }
}
public class ExampleEnum {
    public static void main(String[] args) {
        Size size = Size.SMALL;
        System.out.println("The size is " + size);
        System.out.println("The abbreviation is " + size.getAbbreviation());
    }
}

Enum and Inheritance

An Enum can also be used in inheritance. Here is an example:

public enum Shape {
    CIRCLE {
        @Override
        double calculateArea(double arg1, double arg2) {
            double radius = arg1;
            return Math.PI * radius * radius;
        }
    },
    RECTANGLE {
        @Override
        double calculateArea(double arg1, double arg2) {
            double length = arg1;
            double width = arg2;
            return length * width;
        }
    },
    TRIANGLE {
        @Override
        double calculateArea(double arg1, double arg2) {
            double base = arg1;
            double height = arg2;
            return 0.5 * base * height;
        }
    };
    abstract double calculateArea(double arg1, double arg2);
}
public class ShapeCalculator {
    public static void main(String[] args) {
        double circleArea = Shape.CIRCLE.area(5.0);
        double rectangleArea = Shape.RECTANGLE.area(4.0, 6.0);
        double triangleArea = Shape.TRIANGLE.area(3.0, 4.0);
        System.out.println("Circle area: " + circleArea);
        System.out.println("Rectangle area: " + rectangleArea);
        System.out.println("Triangle area: " + triangleArea);
    }
}

Enums With Example

Enums in Control Flow Statements

Enums can also be used in control flow statements in Java. Here is an example:

public enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class ExampleEnum {
    public static void main(String[] args) {
        DayOfWeek day = DayOfWeek.FRIDAY;
        switch (day) {
            case MONDAY:
                System.out.println("It's Monday");
                break;
            case TUESDAY:
                System.out.println("It's Tuesday");
                break;
            case WEDNESDAY:
                System.out.println("It's Wednesday");
                break;
            case THURSDAY:
                System.out.println("It's Thursday");
                break;
            case FRIDAY:
                System.out.println("It's Friday");
                break;
            case SATURDAY:
                System.out.println("It's Saturday");
                break;
            case SUNDAY:
                System.out.println("It's Sunday");
                break;
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}

For Loop Statement

Here is an example of using a for-loop statement with an Enum in Java:

public class EnumExample {
    public enum Month {
        JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
        JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
    }
    public static void main(String[] args) {
        for (Month month : Month.values()) {
            System.out.println(month);
        }
    }
}

Standard Enum Methods

Here is an example of how to use some of the standard Enum methods in Java:

public enum Size {
    SMALL, MEDIUM, LARGE, XLARGE;
    public static Size fromString(String sizeString) {
        for (Size size : Size.values()) {
            if (size.toString().equalsIgnoreCase(sizeString)) {
                return size;
            }
        }
        throw new IllegalArgumentException("No Enum constant Size." + sizeString);
    }
}

Enum in a Switch Statement

Here is an example of how to use an Enum in a switch statement in Java:

public Enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class Example {
    public static void main(String[] args) {
        DayOfWeek day = DayOfWeek.THURSDAY;
        switch (day) {
            case MONDAY:
                System.out.println("Today is Monday");
                break;
            case TUESDAY:
                System.out.println("Today is Tuesday");
                break;
            case WEDNESDAY:
                System.out.println("Today is Wednesday");
                break;
            case THURSDAY:
                System.out.println("Today is Thursday");
                break;
            case FRIDAY:
                System.out.println("Today is Friday");
                break;
            case SATURDAY:
                System.out.println("Today is Saturday");
                break;
            case SUNDAY:
                System.out.println("Today is Sunday");
                break;
            default:
                System.out.println("Invalid day of week");
        }
    }
}

Conclusion

We hope that this tutorial will be helpful to programming enthusiasts who are looking for reliable sources to master Enum in Java. To be a professional computer science expert, you must seek guidance from experts in the said field.

Several online learning platforms, such as upGrad, offer well-designed programming courses. Enrol in their courses to unlock the best learning benefits!

FAQs

1. Can you define an Enum inside a class in Java?

Yes, you can define an Enum inside a class in Java. This can be useful if the Enum is closely related to the class. Also, the Enum should not be used outside of it.

2. Can Enums inherit from other Enums in Java?

No, Enums cannot inherit from other Enums in Java. However, you can define a class hierarchy and have an Enum implement an interface or extend a class.

3. Are Enums mutable or immutable in Java?

Enums are immutable in Java. This means that their values cannot be changed once they are defined. However, it is possible to make an Enum mutable. It can be done by adding setter methods or making its fields public.

Leave a Reply

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