×

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to Enum in java along with example programs

Let us first know what is Enum.

Enum

A data type in Java called Enum has a predetermined set of constants.

Java Enums can indeed be compared to classes that contain a predetermined collection of constant (a constant: a variable that never changes). Implicitly, the Java enum values are static and final. It has been accessible since JDK 1.5.

Enums are employed to design custom data types, much like classes. In Java, an enum is defined using the enum data type, also referred to as the Enumerated Data Type. Enum in Java is much more versatile than it is in C/C++. Here, we have the option of defining an enum either within or outside of the class.

Let us discuss a simple example program for Java Enum

File name: Enum.java

class Enum
{  
// the class's definition of the enum
public enum Subject { Java, DBMS, Python, HTML }  
public static void main(String[] args) 
{  
// going through the enum
for (Subject s : Subject.values())  
System.out.println(s);  
}
 }  

Output

Java
DBMS
Python
HTML

Note: At compile time, the Java compiler dynamically adds the values(), function valueOf(), as well as ordinal() methods in within enum. For the enum, it internally produces a static but also final class.

Enums typically contain its unique string values, but we can also give them some unique values. Take the example below as evidence.

Example

enum  Planets
{
    Earth(“Blue”), Mars(“Red”), Saturn(“Yellow”);
}

With their own unique custom values of Blue, Red, and Yellow, respectively, Earth, Mars, and Saturn are the three members of the Planets enum in the example above.

There are a few guidelines we must adhere to in order to implement this enum in code:-

  • For this enum class, a parameterized constructor must be created. Because,  Given that we are aware that the objects of the enum class cannot be created explicitly, we utilize the parameterized constructor to initialize the objects. Additionally, the constructor had to have private or basic modifiers and cannot be public or protected. Why? We can initialize many objects if we construct public or protected. This completely violates the enum idea.
  • To determine the value of enums, single getter method must be created.

We updated the public interface of our enum by including fields and functions. As a result, the fundamental Enum name() and function valueOf()  methods used in our code aren't aware of the new fields.

We cannot supply our own function valueOf() implementation because the Java language has already defined the static function valueOf() method for us.

Similarly, we are unable to alter the Enum.name() method because it is final.

Enum values are only repeated several times once as a result of caching, which simplifies the valueOfLabel() method.

As an option in contrast, we can construct the cache asynchronously when the valueOfLabel() method accesses it for the first time. In that instance, synchronising map access is necessary to avoid concurrent issues.

As a result, utilising the regular Enum API to access our additional data is not a viable option. Instead, let's examine some alternative methods for making our fields visible.

Let us go through a simple example program

File name: TrafficSignal.java

// Program written in Java to show how values can be allocated to enums.
enum TrafficSignal
{
// The enum constructor will be invoked with a single String argument.
RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN");
// defining a private variable and retrieving its values
private String action;
// getter approach
public String getAction()
{
return this.action;
}
// Enum constructors cannot be shielded or made public.
private TrafficSignal(String action)
{
this.action = action;
}
}
public class EnumConstructorExample
{
public static void main(String args[])
{
// Let's display the description of the each enum and an explanation of its action: Enum //values()
TrafficSignal[] signals = TrafficSignal.values();


for (TrafficSignal signal : signals)
{
// To obtain the value, utilise the getter method.
System.out.println("name : " + signal.name() +
" action: " + signal.getAction() );
}
}
}

Output

name : RED action: STOP
name : GREEN action: GO 
name : ORANGE action: SLOW DOWN 

Related Topics

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

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

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.

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.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

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

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.