×

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

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.