0% found this document useful (0 votes)
23 views13 pages

Understanding Java Enums and Usage

enum data type in c language

Uploaded by

rajput.patial
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views13 pages

Understanding Java Enums and Usage

enum data type in c language

Uploaded by

rajput.patial
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

enum in Java

Last Updated : 05 Sep, 2024



In Java,Enumerations or Java Enum serve the purpose of representing a


group of named constants in a programming language. Java Enums are used
when we know all possible values at compile time, such as choices on a
menu, rounding modes, command-line flags, etc.

What is Enumeration or Enum in Java?

A Java enumeration is a class type. Although we don’t need to instantiate an


enum using new, it has the same capabilities as other classes. This fact
makes Java enumeration a very powerful tool. Just like classes, you can give
them constructors, add instance variables and methods, and even implement
interfaces.

Enum Example:

The 4 suits in a deck of playing cards may be 4 enumerators named Club,


Diamond, Heart, and Spade, belonging to an enumerated type named Suit.
Other examples include natural enumerated types (like the planets, days of
the week, colors, directions, etc.).

One thing to keep in mind is that, unlike classes, enumerations neither inherit
other classes nor can get extended(i.e become superclass). We can also add
variables, methods, and constructors to it. The main objective of an enum is to
define our own data types(Enumerated Data Types).

Declaration of enum in Java

Enum declaration can be done outside a class or inside a class but not inside
a method.

1. Declaration outside the class

Java
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color {
RED,
GREEN,
BLUE;
}

public class Test {


// Driver method
public static void main(String[] args) {
Color c1 = [Link];
[Link](c1);
}
}

Output
RED

2. Declaration inside a class


Java
// enum declaration inside a class.
public class Test {
enum Color {
RED,
GREEN,
BLUE;
}

// Driver method
public static void main(String[] args) {
Color c1 = [Link];
[Link](c1);
}
}

Output
RED

● The first line inside the enum should be a list of constants and then
other things like methods, variables, and constructors.
● According to Java naming conventions, it is recommended that we
name constant with all capital letters

Properties of Enum in Java

There are certain properties followed by Enum as mentioned below:

● Class Type: Every enum is internally implemented using the Class


type.
● Enum Constants: Each enum constant represents an object of type
enum.
● Switch Statements: Enum types can be used in switch statements.
● Implicit Modifiers: Every enum constant is implicitly public static
final. Since it is static, it can be accessed using the enum name.
Since it is final, enums cannot be extended.
● Main Method: Enums can declare a main() method, allowing direct
invocation from the command line.

Below is the implementation of the above properties:

Java
// A Java program to demonstrate working on enum
// in a switch case (Filename [Link])

import [Link];

// An Enum class
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}

// Driver class that contains an object of "day" and


// main().
public class Test {
Day day;

// Constructor
public Test(Day day) {
[Link] = day;
}

// Prints a line about Day using switch


public void dayIsLike() {
switch (day) {
case MONDAY:
[Link]("Mondays are bad.");
break;
case FRIDAY:
[Link]("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
[Link]("Weekends are best.");
break;
default:
[Link]("Midweek days are so-so.");
break;
}
}

// Driver method
public static void main(String[] args) {
String str = "MONDAY";
Test t1 = new Test([Link](str));
[Link]();
}
}

Output
Mondays are bad.

Java Enum Programs

1. Main Function Inside Enum

Enums can have a main function, allowing them to be invoked directly from the
command line.

Below is the implementation of the above property:


Java
// A Java program to demonstrate that we can have
// main() inside enum class.

public enum Color {


RED,
GREEN,
BLUE;

// Driver method
public static void main(String[] args) {
Color c1 = [Link];
[Link](c1);
}
}

Output

RED

The above program will not run on online compiler. To run this program, save
it as [Link] and use the java command to compile and execute.

2. Loop through Enum

We can iterate over the Enum using the values() method, which returns an
array of enum constants.

Below is the implementation of the loop through Enum:

Java
// Java Program to Print all the values
// inside the enum using for loop
import [Link].*;

// Enum Declared
enum Color {
RED,
GREEN,
BLUE;
}

// Driver Class
class GFG {

// Main Function
public static void main(String[] args) {
// Iterating over all the values in
// enum using for loop
for (Color var_1 : [Link]()) {
[Link](var_1);
}
}
}

Output
RED
GREEN
BLUE

3. Enum in a Switch Statement

Enums can be used in switch statements to handle different cases based on


the enum constants.

Java
// Java Program to implement
// Enum in a Switch Statement
import [Link].*;

// Driver Class
class GFG {
// Enum Declared
enum Color {
RED,
GREEN,
BLUE,
YELLOW;
}

// Main Function
public static void main(String[] args) {
Color var_1 = [Link];

// Switch case with Enum


switch (var_1) {
case RED:
[Link]("Red color observed");
break;
case GREEN:
[Link]("Green color observed");
break;
case BLUE:
[Link]("Blue color observed");
break;
default:
[Link]("Other color observed");
}
}
}

Output
Other color observed

Enum and Inheritance


● All enums implicitly extend [Link] class. As a class can
only extend one parent in Java, an enum cannot extend anything
else.
● toString() method is overridden in [Link] class, which
returns enum constant name.
● enum can implement many interfaces.

Enum and Constructor

● Enums can contain constructors, which are called separately for


each enum constant at the time of enum class loading.
● We can’t create enum objects explicitly and hence we can’t invoke
the enum constructor directly.

Enum and Methods

Enums can have both concrete and abstract methods. If an enum class has
an abstract method, each enum constant must implement it.

Java
// Java program to demonstrate that enums can have
// constructor and concrete methods.

// An enum (Note enum keyword in place of class keyword)


enum Color {
RED,
GREEN,
BLUE;

// Enum constructor called separately for each


// constant
private Color() {
[Link]("Constructor called for : " + [Link]());
}
public void colorInfo() {
[Link]("Universal Color");
}
}

public class Test {


// Driver method
public static void main(String[] args) {
Color c1 = [Link];
[Link](c1);
[Link]();
}
}

Output
Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Note: While the set of constants in a Java enum is fixed at runtime and
cannot be changed dynamically, you can modify the source code of the enum
to add or remove constants and then recompile the application to reflect these
changes.

Creating a Class with Enum Member

When combined with classes, enum can serve as powerful tool for organising
program.

Java
/*package whatever //do not write package name here */

import [Link].*;

enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}

public class EnumTest {


// Enum member variable
Day day;

// constructor which takes enum value


public EnumTest(Day day) { [Link] = day; }

// method to execute action as per enum value


public void tellItLikeItIs()
{
switch (day) {
case MONDAY:
[Link]("Mondays are tough");
break;
case TUESDAY:
[Link]("Tuesday are better");
break;
case WEDNESDAY:
[Link]("Wednesday are okay");
break;
case THURSDAY:
[Link]("Thursdays are hopeful");
break;
case FRIDAY:
[Link]("Fridays are exciting");
break;
case SATURDAY:
[Link]("Saturdays are relaxing");
break;
case SUNDAY:
[Link]("Sunday are for rest");
break;
default:
[Link]("Everyday are good");
break;
}
}

public static void main(String[] args)


{
EnumTest firstDay = new EnumTest([Link]);
[Link]();

EnumTest thirdDay = new EnumTest([Link]);


[Link]();

EnumTest fifthDay = new EnumTest([Link]);


[Link]();

EnumTest sixthDay = new EnumTest([Link]);


[Link]();

EnumTest seventhDay = new EnumTest([Link]);


[Link]();
}
}

Output
Mondays are tough
Wednesday are okay
Fridays are exciting
Saturdays are relaxing
Sunday are for rest

The EnumTest class in above code is created with member of type Day. It has
constructor which takes Day enum as an argument and assigns it.

The class has method tellItLikeItIs(), which prints message based on value of
day.
The main method includes objects of EnumTest using different Day enum
values and calling tellItLikeItIs() method on each.

NOTE: In the main method new is used when creating instances of EnumTest
because EnumTest is a regular Java class not enum itself. So, the new
keyword is used to create new instance of EnumTest class, and passing enum
value to its constructor.

Common questions

Powered by AI

Declaring an enum within a class confines the enum's accessibility to that class, promoting encapsulation when the enum's use case is tightly coupled with the class's functionality. This provides logical grouping, especially when the enums are specific to class operations, enhancing maintainability and reducing global namespace pollution. Declaring an enum outside of a class makes it accessible globally, suitable for reusable constants across multiple classes. However, this could lead to potential namespace conflicts or unnecessary exposure of internals. Choosing between these patterns depends on the scope requirements and logical design of the application .

Including a main method within a Java enum class allows the enum to be executed directly from the command line, which is unique for a type that primarily represents constant values. This enables developers to encapsulate test or demonstration logic pertinent to the enum directly within the enum class itself, promoting encapsulation and ease of maintenance. However, this implies the enum class should contain execution logic pertinent to the constants it represents, rather than general application logic, to maintain clean code and separation of concerns .

Java enums can be used in switch statements as switch cases directly reference enum constants, enhancing readability and maintainability by avoiding literal strings or integers. However, each case must be explicitly defined and handled, meaning developers should anticipate all potential enum values to prevent fall-through behavior. Enum constants in switch cases are resolved at compile-time, enabling efficient dispatch but are also immutable at runtime, meaning the set of enum constants is constant after class loading .

Using Java enums is inappropriate when the set of values might change dynamically at runtime, as enums do not support adding or removing constants once loaded, limiting flexibility for varying business logic or data-driven programs. Developers might prefer classes or data structures like lists or sets for scenarios requiring dynamic handling of elements. Additionally, if you require a hierarchical type system with polymorphic behavior not supported via interfaces, a traditional class hierarchy might be more appropriate .

Java enums can include constructors much like regular classes, and these constructors are implicitly invoked for each enum constant at the time of enum class loading. Developers cannot explicitly call these enum constructors, nor can they create new enum instances using 'new', as enum constants are static final and predefined at compile-time. This restriction helps ensure that the fixed set of constants in an enum remains consistent, maintaining the integrity of the enumerated type .

The use of the values() method in Java enums offers the benefit of easy iteration over all constants, enhancing code clarity and reducing errors related to hardcoding values. However, a potential drawback is that the array returned by values() is a fresh copy each time, which might result in unnecessary memory allocation when iterated over frequently in memory-intensive applications. Additionally, any changes made to the array have no effect on the actual enum constants, maintaining data integrity at the cost of mutable operation potential .

Immutability of enum constants enhances application security by preventing alterations that could introduce inconsistencies or bugs, as enum objects are constant and cannot be modified after their definition. This characteristic significantly reduces the risk of unintended side effects caused by modifying shared data among different parts of an application. Performance is positively impacted by guaranteeing that the immutable nature of enums requires no extra synchronization overhead in concurrent environments, while ensuring stability and predictability across threads .

Java enums provide compile-time type safety, ensuring that only valid constants are used, unlike static final fields that are prone to errors due to possible mismatches in expected values. Enums offer additional functionality, including internal methods, constructors, and the ability to be used in switch statements, providing both a type-safe and extensible way to group related constants. Moreover, enums inherently ensure no duplication of constants, which can occur with static fields. Therefore, enums optimize code readability, maintainability, and error prevention compared to static final constants .

Java enums can implement interfaces, allowing them to have methods just like classes. By implementing interfaces, enums can share common behavior across different enum constants. This approach provides flexibility, allowing for varying behavior among constants if desired by overriding methods for specific constants. The advantage for developers is a powerful design pattern where enums can conform to a particular contract or behavior without needing superclass inheritance, allowing each enum to possess both type-safe constant values and customizable functionality .

Java enums cannot be extended themselves nor can they extend any other class besides the implicit superclass java.lang.Enum, because in Java a class can only extend one other class. This restriction signifies that enums do not have class inheritance in the traditional sense but can only be extended by implementing interfaces. The implication for developers is that enums are designed for a specific and limited use case - that of representing fixed sets of constants, which promotes simplicity and limits possible inheritance-based design complications .

You might also like