×

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

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

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

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

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

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.