Enumeration in Java

Enumeration in Java
Enumeration in Java

Introduction

In most programming languages, we can create user-defined data types on top of inbuilt data types to accommodate data constituted with various data types. Enum is one such example of user-defined data types in Java. It was introduced in version 5 of the JDK in 2004. Using enums makes the code simple, small, and efficient.

What is Enumeration in Java? 

Java enums are classes with a fixed set of constants or variables with no tendency to change. These enum constants in Java are static and final implicitly. The above phrase, “fixed set of constants,” highlights that we should have all possible constants at the compile time for enum. However, the set of constants can be modified over time. And the phrase “final” implies that we can’t create child enums.

Defining Java Enum and its Syntax

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.

Let’s go through the syntax for the enum-

enum enumname {CONSTANT1, CONSTANT2,..... ;}

Why do we need java enum?

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-

blog banner 1
Enter the drawn card:
HEART

Output-

We got a HEART.

Other 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.

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

Advantages of Java enums

Let’s see the advantages of using Java enums. They increase the type safety significantly, are highly suitable for switch cases, we can use them to traverse the loops, and they could also have methods, constructors, and fields.

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.

How do you create an enum constant in Java?

To create an enum constant in Java, we use the following syntax-
enum enumname {CONSTANT1, CONSTANT2,….. ;}

How does Java enum valueOf() work?

The valueOf() method in the Java enum takes a string input and checks if the string corresponds to any constant in the class. If yes, the constant is returned, and if there is no corresponding constant, it throws an exception.

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.

Key Takeaways

In this blog, we learned about the Java enums-

We started with knowing what Java Enums are, how they work, why do we need them? Then we moved on to the different uses of java enums and how we can implement them. We learned that it is highly suitable for switch cases, if-else if statements, customization of values assigned to the constants, and inheritance of Java enums. Then we saw the implementation of methods like the value of values(), valueOf(), ordinal(). These methods enhance the scope of problems we can solve with the help and help improve the code’s efficiency.

Visit here to learn more about oops in Java. You can also practice numerous programming problems on CodeStudio. If you liked this blog, share it with your friends.

By: Gorakhnathh Yadav