×

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

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 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.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.