×

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 Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.