Java

Java Enum 101 : Explained with easy examples

Understanding JAVA Enum

Java Enum or Enumeration are mainly used to define some set of named constants that fall under the same group. It is a special type of Java class.

What is java enum?

If I were to give a real-world example, you can consider a set of animals, which can have different names but fall under the same category of animals (ex – horse, goat, cow, lion etc). Here different animals can be referred to as enumerators and the “animals” category as an enumerated type.

The main motive of having enums in JAVA is to be able to define our own data types. It was added in Java version 5 and above.

Simplest java enum example

One simple enum example could be an enum that has different sizes under it. This could be useful if you are creating a web application for an e-commerce platform and in similar use cases.

public enum SIZE {
    LARGE,
    SMALL,
    MEDIUM
}

The enum keyword has a special meaning here. It informs the compiler that similar to other classes or interfaces, we are defining java enum as well.

How to assign value to an enum type?

Now how do we use an enum, or refer to one of the values in it? Just create an Enum object with the required enum value.

Size size = Size.SMALL;

In the above case, the size variable is of type Size and has been assigned a small value. We can assign LARGE and MEDIUM similarly.

How to declare an enum?

Few things to consider while declaring an enum in java :

Example:

If declared outside a class.

enum Size
{
    SMALL, MEDIUM, LARGE;
}
  
public class Test
{
    public static void main(String[] args)
    {
        Size size = Size.MEDIUM;
        System.out.println(size);
    }
}

//output MEDIUM

If declared within a class.

public class Test 
{
  enum Size { 
    SMALL, MEDIUM, LARGE; 
  } 

  public static void main(String[] args) 
  { 
     Size size = Size.MEDIUM; System.out.println(size); 
  } 
} 
//output MEDIUM
  • The first line of an enum data type should be the list of comma-separated constants. After that one can define custom methods and other things.
  • Convention for declaring an enum is that constants should be always capitalized.
  • An enum is by default private static final hence. Therefore values or constants are accessed using enum name dot constant name.
  • Since it is implicitly declared as final, child enums cannot be created.
  • Enums can be compared by using:
    • == Operator
    • or .equals() method.
  • We can also declare main() method within an enum as we would do in a class.
    enum Size
    {
        MEDIUM, SMALL, LARGE;
      
        // Driver method
        public static void main(String[] args)
        {
            Size size = Size.MEDIUM;
            System.out.println(size);
        }
    }
    //output MEDIUM
  • Enum in java cannot extend any other class, as it already extends java.lang.Enum. However it can implement interfaces if required.

 

Methods of enum in java:

[su_note note_color=”#ffffff” text_color=”#000000″]

  • values()– Values method is used to get all the values of an enum.
  • ordinal()– This method is used to determine the index of a constant in an enum
  • valueOf()– Given a string, it returns the constant equivalent of that string.
  • A java enum can have custom methods that can be user-defined.
  • When defining enum with custom methods, the constants list must end with a semicolon(;).
  • An enum can contain abstract methods too. The constraint with this is all instances of the enum class will have to implement abstract methods.
  • Custom constructors can also be defined. Default constructor can be overloaded with parameterized constructors.
  • When the enum is called, it will call the constructor for all the respective constants of enum one by one during class loading.
  • Custom constructors defined has to be private.
  • Since there cannot be enum constructors we cannot invoke constructors directly.
  • Enum in Java is type-safe. You cannot assign any other value apart from the values specified in the enum.

[/su_note]

Example of user-defined method within an enum :

enum Size
{
    SMALL, MEDIUM, LARGE;
 
    private Size()
    {
        System.out.println("Size constructor initialized : " +
        this.toString());
    }
  
    public void sizeDetails()
    {
        System.out.println("Covers size for all age groups!");
    }
}
  
public class Sizes
{    
    public static void main(String[] args)
    {
        Size size = Size.SMALL;
        System.out.println(size);
        size.sizeDetails();
    }
}

Output:

Size constructor initialized : SMALL
Size constructor initialized : MEDIUM 
Size constructor initialized : LARGE 
Covers size for all age groups!

Defining customized enum in java:

All the above examples used the constants as default values for enums but java enum also supports custom values. We will take a look at how to define such enums, with the example where:

  • We will have an enum of books
  • Each member of the enum will be a programming language book name.
  • Each book will have its own author
enum Books
{
    JAVA(“AUTHOR 1”), CPP(“AUTHOR 2”), PYTHON(“AUTHOR 3”);
}

Few pre-requisite for having a custom enum with values are:

[su_note note_color=”#ffffff” text_color=”#000000″]

  • Enum should have a member variable to save value of constant.
  • Enum should have a parametrized constructor initializing the created member variable.
  • It should have a getter exposing member variable value.

[/su_note]

Example :

public enum JavaWorkshop {
 
    JAVA("Author 1"), CPP("Author 2"), PYTHON("Author 3");
 
    private String programmingLangAuthor;
 
    private JavaWorkshop(String s) {
        programmingLangAuthor = s;
    }
 
    public String getProgrammingLang() {
        return programmingLangAuthor;
    }
}

Then using it in a class.

public class JavaWorkshopExample {
 
    public static void main(String[] args) {
        System.out.println("Get author of book 'JAVA': "
                + JavaWorkshop.JAVA.getProgrammingLang());
    }
 
}

Output:

Get author of book 'JAVA': Author 1

Few Faqs related to Enum in java :

When to use java enum?

Enums are useful and can be used only when the use case satisfies certain criteria.

  • If all the possible constant values are known beforehand.
  • If a class has to use one value at a time from a list of constants.
  • The same set of constants are to be used at multiple places within a class or in multiple classes.

Is enum immutable?

Enum in java is tightly immutable. They expose certain methods which can be used to get all the values of an enum. This array of values can be used to create a new enum with some additional values as a workaround.

Can enum in java be null?

Yes, a java enum can be null. When a field of type enum is created in a class but not initialized, by default it is null.

Why java enum?

Because they enable reusability and hence better code readability. And them being immutable add an extra layer of reliability for the constants defined within code.

Let’s Discuss

If you liked the tutorial, feel free to share it on social media. If you have any doubts or something is missing from the post, leave them in the comments below.

Related posts:

java get hostname
Java

Ways in JAVA to get hostname, localhost and IP Address

Here’s a guide with multiple examples in JAVA to get hostname or IP address from URL or localhost using JAVA
Best class to java decompilers
Java

Best class to java decompilers : Try online or download free

If you are a programmer or even a beginner in this field of programming, then you probably would have heard