×

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond, Heart, and Spade, members of the enumerated type Suit. The enumerated natural kinds are another example (like the galaxies, weeks in a month, colours, etc.).

When we know every potential value at compilation time, such as for menu options, rounding modes, command-line flags, etc., enums are employed. An enum type's constants need not always remain consistent over time.

Enumerations in Java are class types. Enums have the same features as other classes even though we don't need to instantiate them using new ones. Java enumeration is an extremely potent tool as a result of this feature. They can have constructors, instance variables, and methods added, just like classes, and you can even create interfaces.

Unlike classes, enumerations cannot inherit from other classes or be expanded, which is something to keep in mind (i.e. become superclass).

Enums are expressed using the enum data type in Java. Enums in Java are more capable than those in C/C++. Variables, methods, and constructors can all be added in Java. Enum's primary goal is to allow us to create custom data types (Enumerated Data Types).

Java declaration of an enum

Enum declarations are permitted both inside and outside of classes but not inside of methods.

// An example of a simple enum when the enum is declared
// not in a class (Note that enum is
// the term here instead of class.)
enum Days {
Sun,
Mon,
Tue;
}
public class Kamal {
// method of the Driver
public static void main(String[] args)
{
Days d1 = Days.Sun;
System.out.println(d1);
}
}

Output:

Enumeration Java
// inside of a class, an enum declaration
public class Test1 {
    enum Days {
        Sun,
        Mon,
        Tue;
    }
    // method of the driver
    public static void main(String[] args)
    {
        Days d1 = Days.Sun;
        System.out.println(d1);
    }
}

Output:

Enumeration Java
  • Constants should appear on the first line of the enum, followed by a list of variables, constructors, and other items.
  • According to Java naming conventions, it is recommended that we name constant with all capital letters.

Important Points to Remember

  • Every enum has a Class implementation on the inside.
/* in the internal enum Days is changed into a class of Days.
{
     public static final Day Sun = new Day();
     public static final Day Mon = new Day();
     public static final Day Tue = new Day();
}*/
  • An object of the type enum is represented by each enum constant.
  • Switch statements accept arguments of any type, including enum types.
// a Java programme that shows how to interact 
// with enums in switch cases (Filename Test3. Java)
import java.util.Scanner;
// An Enum class
enum Days {
    SUN,
    MON,
    TUE,
    WED,
    THU,
    FRI,
    SAT;
}
// a class of drivers that includes an object for "days" and
// the main().
public class Test3 {
    Days days;
    // Constructor
    public Test(Days days) { this.days = days; } 
    // the switch is used to print a sentence regarding Days.
    public void daysIsLike()
    {
        switch (days) {
        case MON:
            System.out.println("Mon are very boring.");
            break;
        case FRI:
            System.out.println("Fri are the best.");
            break;
        case SAT:
        case SUN:
            System.out.println("Weekends are the best.");
            break;
        default:
            System.out.println("Midweek days are so-so days.");
            break;
        }
    }
    // method of the driver
    public static void main(String[] args)
    {
        String str = "MON";
        Test3 t1 = new Test3(Days.valueOf(str));
        t1.daysIsLike();
    }
}

Output:

Enumeration Java
  • All enum constants are inherently static public final. The enum Name can be used to access it because it is static. We cannot make child enums because it is final.
  • The enum can contain a declaration for the main() method. So, using the Command Prompt, we can call enum.
// A Java application to show that main() can be 
// contained within an enum class.
enum Days {
    SUN,
    MON,
    TUE;
    // method of the driver
    public static void main(String[] args)
    {
        Days d1 = Days.SUN;
        System.out.println(d1);
    }
}

Output:

Enumeration Java

enum and the constructor:

  • When the enum class is loaded, enums are allowed to have constructors, which are executed individually for each enum constant.
  • Enum constructors cannot be called directly since we cannot explicitly create enum objects.

enum and the methods:

  • enum can contain both concrete methods and abstract methods. If an enum class has an abstract method, then each instance of the enum class must implement it.
// Enums can have concrete methods and 
// constructors, as shown by a Java programme. 
// an enum (Note that enum is used in instead of class.)
enum Days {
    Sun,
    Mon,
    Tue;
    private Days()
    {
        System.out.println("Constructor called for : "
                           + this.toString());
    }
    public void daysInfo()
    {
        System.out.println("Universal Days");
    }
}
public class Test4 {
    // method of the driver
    public static void main(String[] args)
    {
        Days d1 = Days.Sun;
        System.out.println(d1);
        c1.daysInfo();
    }
}

Output:

Enumeration Java

Related Topics

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.