×

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond, Heart, and Spade that fall under the umbrella of the enumerated type Suit. Natural enumerated types are another illustration 

When we know every potential value at compilation time, such as for menu options, rounded modes, command-line flags, etc., Enums are employed. An Enum type's set of constants need not always remain consistent over time.

A class type in Java is an enumeration. Although we don't need to use new to create an instance of an Enum, it can still perform the same functions as other classes. Enumeration in Java is a very effective tool because of this aspect. They can have constructors, instance variables, and methods added, just like classes, and you can even create interfaces.

Keep in mind that enumerations cannot inherit from other classes or be expanded, unlike classes (i.e. become superclass).

Enums are expressed in Java (as of 1.5) using the Enum data type. Enums in Java are more capable than those in C/C++. Variables, methods, as well as constructors, can all be added to it in Java. Enum's primary goal is to allow us to create custom data types (Enumerated Data Types).

Example 1

enumColor {
	BLUE,
	GREEN,
	PINK;
}
public class Test {
	public static void main(String[] args)
	{
		Color c1 = Color.BLUE;
		System.out.println(c1);
	}
}

Output

BLUE

Example 2

Internally, each Enum is implemented using a Class.

An object of the type enum is represented by each enum constant.

Switch statements accept arguments of the enum type.

import java.util.Scanner;
enum Day {
	SUNDAY,
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY,
	SATURDAY;
}
public class Test {
	Day day;
	public Test(Day day) { this.day = day; }
	public void dayIsLike()
	{
		switch (day) {
		case MONDAY:
			System.out.println("Mondays are good.");
			break;
		case FRIDAY:
			System.out.println("Fridays are better.");
			break;
		case SATURDAY:
		case SUNDAY:
			System.out.println("Weekends are best.");
			break;
		default:
			System.out.println("Midweek days are so-so.");
			break;
		}
	}
	public static void main(String[] args)
	{
		String str = "MONDAY";
		Test t1 = new Test(Day.valueOf(str));
		t1.dayIsLike();
	}
}

Output

Mondays are good.

Example 3

Every enum constant is inherently public static final. The enum Name can be used to access it because it is static. We cannot make child enums because it is final.

The main() method can be declared inside the enum. So, using the Command Prompt, we can just call an enum.

enumColor {
	BLUE,
	BROWN,
	PINK;
	public static void main(String[] args)
	{
		Color c1 = Color.BLUE;
		System.out.println(c1);
	}
}

Output

BLUE

Example 4

Enumerations and Inheritance

Implicitly, every enum extends Java.lang.

  • class enum. An enum never extends anything else, just as a class in Java could only extend oneparent.
  • In Java.lang, the function toString() { [native code] }() method is overridden.Theenum constant name is returned by the enum class.
  • Many interfaces can be implemented with an enum.

The methods values(), ordinal(), and function valueOf()

  • These methods can be found in the Java.lang library.
  • All values contained within the enum can be returned using the enum.values() method.
  • In enums, the order is crucial.
  • Every enum constant index can always be retrieved utilizingthe ordinal() method, exactly like an array index.
  • If an enum constant for the provided string value exists, the function valueOf() { [native code] }() method returns it.
enumColor {
	PINK,
	GREEN,
	BLUE;
}
public class Test {
	public static void main(String[] args)
	{
		Colorarr[] = Color.values();
		for (Color col: arr) {
			System.out.println(col + " at index "
							+ col.ordinal());
		}
		System.out.println(Color.valueOf("PINK"));
	}
}

Output

PINK at index 0GREEN at index 1
BLUE at index 2
PINK

Example 5

Function Object()  and enumerator

Enums are capable of having constructors, which are run independently for every enum constant when the enum class is loaded.

Enum objects cannot be explicitly created, and as a result, their function Object() { [native code] } cannot be called directly.

enum and procedures:

Enum is capable of including both concrete and abstract procedures. Every instance of an enum class that has an abstract data type must implement it.

enumColor {
	RED,
	GREEN,
	BLUE;
	private Color()
	{
		System.out.println("The Constructor called for : "
						+ this.toString());
	}
	public void colorInfo()
	{
		System.out.println("Universal Color");
	}
}
public class Test {
	public static void main(String[] args)
	{
		Color c1 = Color.RED;
		System.out.println(c1);
		c1.colorInfo();
	}
}

Output

Constructor called for: REDConstructor called for: GREEN
The constructor called for: BLUE
RED
Universal Color

Related Topics

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.