×

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

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

How to add 24 Hours to Date in Java?

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

2 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.