You are currently viewing Java enum with Example

Java enum with Example

In this tutorial, we’ll learn about enums in Java. With the help of examples, we will learn how to create and use enums and enum classes.

What is java enum?

A Java Enum is a Java type that is used to define collections of constants. To be more specific, a Java enum type is a subtype of a Java class. Constants, methods, and other data can be stored in an enum. In Java 5, enums were introduced. This Java enums tutorial will show you how to make and use a Java enum.

Note: In Java, an Enum is a data type that contains a fixed set of constants.
  • Enums in Java are classes that have a fixed set of constants (a variable that does not change). Java enum constants are implicitly static and final. 
  • Enums are used to define our own data types, similar to classes. In Java, an enums is defined using the enum data type (also known as Enumerated Data Type). In Java, the enums is more powerful than in C/C++. In this case, we can define an enum either inside or outside the class.
  • Java Enums inherits the Enum class internally, so it cannot inherit any other class, but it can implement a large number of interfaces. In Java enums, we can have fields, constructors, methods, and main methods.

To declare enums, we use the enum keyword. As an example:

enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}

In this case, we’ve created an enum called Size. It has fixed values such as SMALL, MEDIUM, LARGE, and EXTRALARGE.

These values between the braces are known as enum constants (values).

Note: The enum constants are usually represented in uppercase.

Considerations for Java Enum

  • Enum enhances type safety.
  • Enum is a simple type of variable that can be used in a switch.
  • The enumeration can be traversed.
  • Fields, constructors, and methods can all be found in an enum.
  • Enum can implement a large number of interfaces but cannot extend any class because it extends itself. Enumeration class

Example: Java enum

Example 1: Simple example of enum

class EnumExample{  
//defining the enum inside the class  
public enum Season { SUNDAY, MONDAY, SUMMER, PASS }  
//main method  
public static void main(String[] args) {  
//traversing the enum  
for (Season e : Season.values())  
System.out.println(e);  
}}  

Output:

SUNDAY
MONDAY
SUMMER
PASS

Example 2: Java Enum with the switch statement

enum Size {
 SMALL, MEDIUM, LARGE, EXTRALARGE
}

class Test {
 Size BedSize;
 public Test(Size BedSize) {
   this.BedSize = BedSize;
 }
 public void orderBed() {
   switch(BedSize) {
     case SMALL:
       System.out.println("I ordered a small size Bed.");
       break;
     case MEDIUM:
       System.out.println("I ordered a medium size Bed.");
       break;
     default:
       System.out.println("I don't know which one to order.");
       break;
   }
 }
}

class Main {
 public static void main(String[] args) {
   Test t = new Test(Size.MEDIUM);
   t.orderBed();
 }
}

Output:

I ordered a medium size Bed.
  • We created an enum type Size in the preceding program. We then declared a BedSize variable of the Size type.
  • The variable BedSize can only be assigned four values in this case (SMALL, MEDIUM, LARGE, EXTRALARGE).

Take note of the statement:

Test t = new Test(Size.MEDIUM);

It will invoke the Test() constructor from within the Test class. The MEDIUM constant is now assigned to the variable Bedsize.

One of the switch case statements cases is executed based on the value.

Enum Class in Java

Enum types are regarded as a subclass of classes in Java. It debuted with the release of Java 5. An enum class, like any other class, can have methods and fields.

enum Size {
constant1, constant2, …, constantN;
//methods..
}

When we define an enum class, the compiler will generate instances (objects) for each of the enum constants. Furthermore, by default, all enum constants are public static final.

Example 3: Enum Class

enum Size{
  SMALL, MEDIUM, LARGE, EXTRALARGE;

  public String getSize() {

    // this will refer to the object SMALL
    switch(this) {
      case SMALL:
        return "small";

      case MEDIUM:
        return "medium";

      case LARGE:
        return "large";

      case EXTRALARGE:
        return "extra large";

      default:
        return null;
      }
   }

  public static void main(String[] args) {

    // call getSize()
    // using the object Medium
    System.out.println("The size of the Bed is " + Size.Medium.getSize());
  }
}

Output:

The size of the Bed is Medium
  • In the preceding example, we created an enum class called Size. It comes in four sizes: SMALL, MEDIUM, LARGE, and EXTRALARGE.
  • Because Size is an enum class, the compiler generates instances for each enum constant.
  • We used the instance MEDIUM to call the getSize() method within the main() method.

Methods: Java Enum Class

There are some predefined methods in enum classes that can be used right away.

1: Enum values()

When the Java compiler creates an enums, it adds the values() method internally. The values() method returns an array containing all of the enum values.

  • The values() method returns an enum type array containing all of the enum constants. As an example:
Size[] enumArray = Size.value();

2: Java Enum valueOf()

When a Java enum is created, the constructor method is added internally by the Java compiler. The constructor method returns the value of the given constant enum.

  • The constructor method takes a string and returns an enum constant with the same name as the string. As an example:
Size.valueOf(“SMALL”)
// returns constant SMALL.

3: Enum name()

The name() method returns the string representation of an enum constant’s defined name. The value returned by the name() method is final. As an example:

name(SMALL)
// returns “SMALL”

4: Enum toString()

The enum constants’ string representation is returned by the constructor method. As an example:

SMALL.toString()
// returns “SMALL”

5: Java Enum ordinal()

When the Java compiler creates an enum, it adds the ordinal() method internally. The ordinal() method returns the enum value’s index.

The ordinal() method returns the enum constant’s position. As an example:

ordinal(SMALL)
// returns 0

6: Enum compareTo()

The compareTo() method compares the ordinal values of the enum constants. As an example:

Size.SMALL.compareTo(Size.MEDIUM)
// returns ordinal(SMALL) – ordinal(MEDIUM)
Note: At compile time, the Java compiler adds values(), valueOf(), and ordinal() methods to the enum. It generates a static and final class for the enum internally.

Enum Implementing Interface

If it makes sense in your situation, a Java Enum can implement a Java Interface. An example of a Java Enum implementing an interface is shown below:

public enum EnumImplementingInterface implements MyInterface {
    FIRST("First Value"), SECOND("Second Value");


    private String description = null;

    private EnumImplementingInterface(String desc){
        this.description = desc;
    }

    @Override
    public String getDescription() {
        return this.description;
    }
}

The method getDescription() is provided by the interface MyInterface.

Implementing an interface with an Enum could be used to create a collection of different Comparator constants that can be used to sort object collections.

You may like:

Java Inheritance with Example | Types of inheritance

Java final Keyword with Example

Not Equal Example in Java

Java Polymorphism with Example

Singleton Class in Java with Implementation and Example

Java Nested and Inner Class with Example

Hope this article will guide you to recognize all about Java enums with the Example that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has 7 Comments

Leave a Reply