Enum in java

In Java programming, enums (short for enumerated types) are a powerful feature that allows you to define a set of named values as a distinct data type. Enums provide a way to represent a fixed set of constant values, making your code more readable, maintainable, and self-explanatory. In this article, we will dive deep into the world of enums in Java, exploring their syntax, features, benefits, and practical examples. Whether you’re a beginner or an experienced Java developer, understanding enums will significantly enhance your ability to design robust and expressive code. Let’s embark on this enum adventure!

Enum in Java is a list of named constants.in Java, an enum can have constructors, methods, and instance variables

  1. Declaring Enums:
    To declare an enum in Java, use the enum keyword followed by the name of the enum type. Inside the enum, you define the set of constant values, each represented by a unique name. Enums can also include additional properties, methods, and constructors.

Example:

public enum DayOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY;
}
  1. Accessing Enum Values:
    You can access enum values using the dot notation, similar to accessing static fields of a class. Enum values are constants, and you can compare them using the == operator.

Example:

DayOfWeek today = DayOfWeek.MONDAY;
if (today == DayOfWeek.MONDAY) {
    System.out.println("It's Monday!");
}
  1. Enum Constructors and Methods:
    Enums can have constructors and methods, allowing you to add behavior and additional properties to the enum values. You can define custom constructors and methods for each enum value.

Example:

public enum DayOfWeek {
    MONDAY("Mon"),
    TUESDAY("Tue"),
    WEDNESDAY("Wed"),
    THURSDAY("Thu"),
    FRIDAY("Fri"),
    SATURDAY("Sat"),
    SUNDAY("Sun");

    private final String abbreviation;

    DayOfWeek(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation() {
        return abbreviation;
    }
}
  1. Enum Switch Statements:
    Enums work exceptionally well with switch statements, making your code more concise and readable. You can switch on enum values directly, eliminating the need for multiple if-else statements.

Example:

DayOfWeek day = DayOfWeek.WEDNESDAY;
switch (day) {
    case MONDAY:
    case TUESDAY:
    case WEDNESDAY:
    case THURSDAY:
    case FRIDAY:
        System.out.println("It's a weekday");
        break;
    case SATURDAY:
    case SUNDAY:
        System.out.println("It's a weekend");
        break;
}
  1. Enum with Custom Fields and Methods:
    Enums can have custom fields and methods just like regular classes. This allows you to associate additional information with each enum value and perform operations specific to the enum type.

Example:

public enum Coin {
    PENNY(1),
    NICKEL(5),
    DIME(10),
    QUARTER(25);

    private final int valueInCents;

    Coin(int valueInCents) {
        this.valueInCents = valueInCents;
    }

    public int getValueInCents() {
        return valueInCents;
    }
}

Enum Fundamentals

An enum is created using the enum keyword.

enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}

The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants. Each is implicitly declared as a public, static final member of Apple.

Once you have defined an enumeration, you can create a variable of that type. However, even though enumerations define a class type, you do not instantiate an enum using new. Instead, ywe declare and use an enumeration variable in much the same way as you do one of the primitive types. For example, this declares ap as a variable of enumeration type Apple

Apple ap;

Because ap is of type Apple, the only values that it can be assigned (or can contain) are those defined by the enumeration. For example, this assigns ap the value RedDel

ap = Apple.RedDel;

An enumeration value can also be used to control a switch statement. Of course, all of the case statements must use constants from the same enum as that used by the switch expression. For example, this switch is perfectly valid

Use an enum to control a switch statement

switch(ap) {
case Jonathan:
// …
case Winesap:
// …

Example of an enum of apple varieties

enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo {
public static void main(String args[])
{
Apple ap;
ap = Apple.RedDel;
// Output an enum value.
System.out.println("Value of ap: " + ap);
System.out.println();
ap = Apple.GoldenDel;
// Compare two enum values.
if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n");
// Use an enum to control a switch statement.
switch(ap) {
case Jonathan:
System.out.println("Jonathan is red.");
break;
case GoldenDel:
System.out.println("Golden Delicious is yellow.");
break;
case RedDel:
System.out.println("Red Delicious is red.");
break;
case Winesap:
System.out.println("Winesap is red.");
break;
case Cortland:
System.out.println("Cortland is red.");
break;
}
}
}

Value of ap: RedDel
ap contains GoldenDel.
Golden Delicious is yellow

The values( ) and valueOf( ) Method

All enumerations automatically contain two predefined methods: values( ) and valueOf( )

The following program demonstrates the values( ) and valueOf( ) methods

enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo2 {
public static void main(String args[])
{
Apple ap;
System.out.println("Here are all Apple constants:");
// use values()
Apple allapples[] = Apple.values();
for(Apple a : allapples)
System.out.println(a);
System.out.println();
// use valueOf()
ap = Apple.valueOf("Winesap");
System.out.println("ap contains " + ap);
}
}

Output

Here are all Apple constants:
Jonathan
GoldenDel
RedDel
Winesap
Cortland


ap contains Winesap

Java Enumerations Are Class Types

A Java enumeration is a class type. Although you don’t instantiate an enum using new, it otherwise has much the same capabilities as other classes. The fact that enum defines a class gives powers to the Java enumeration that enumerations

Use an enum constructor, instance variable, and method

enum Apple {
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);
private int price; // price of each apple
// Constructor
Apple(int p) { price = p; }
int getPrice() { return price; }
}
class EnumDemo3 {
public static void main(String args[])
{
Apple ap;

// Display price of Winesap.
System.out.println(“Winesap costs ” +
Apple.Winesap.getPrice() +
” cents.\n”);
// Display all apples and prices.
System.out.println(“All apple prices:”);
for(Apple a : Apple.values())
System.out.println(a + ” costs ” + a.getPrice() +
” cents.”);
}
}

Output

Winesap costs 15 cents.
All apple prices:
Jonathan costs 10 cents.
GoldenDel costs 9 cents.
RedDel costs 12 cents.
Winesap costs 15 cents.
Cortland costs 8 cents.

Enumerations Inherit Enum

Although we can’t inherit a superclass when declaring an enum, all enumerations automatically inherit one: java.lang.Enum. This class defines several methods that are available for use by all enumerations

we can obtain a value that indicates an enumeration constant’s position in the list of constants. This is called its ordinal value, and it is retrieved by calling the ordinal( ) method

final int ordinal( )

An enumeration of apple varieties

enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo4 {
public static void main(String args[])
{
Apple ap, ap2, ap3;
// Obtain all ordinal values using ordinal().
System.out.println("Here are all apple constants" +
" and their ordinal values: ");
for(Apple a : Apple.values())
System.out.println(a + " " + a.ordinal());
ap = Apple.RedDel;
ap2 = Apple.GoldenDel;
ap3 = Apple.RedDel;
System.out.println();
// Demonstrate compareTo() and equals()
if(ap.compareTo(ap2) < 0)
System.out.println(ap + " comes before " + ap2);
if(ap.compareTo(ap2) > 0)
System.out.println(ap2 + " comes before " + ap);
if(ap.compareTo(ap3) == 0)
System.out.println(ap + " equals " + ap3);
System.out.println();
if(ap.equals(ap2))
System.out.println("Error!");
if(ap.equals(ap3))
System.out.println(ap + " equals " + ap3);
if(ap == ap3)
System.out.println(ap + " == " + ap3);
}
}

The output from the program

Here are all apple constants and their ordinal values:
Jonathan 0
GoldenDel 1
RedDel 2
Winesap 3
Cortland 4
GoldenDel comes before RedDel
RedDel equals RedDel
RedDel equals RedDel
RedDel == RedDel

Another Enum Example

import java.util.Random;
// An enumeration of the possible answers.
enum Answers {
NO, YES, MAYBE, LATER, SOON, NEVER
}
class Question {
Random rand = new Random();
Answers ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 15)
return Answers.MAYBE; // 15%
else if (prob < 30)
return Answers.NO; // 15%
else if (prob < 60)
return Answers.YES; // 30%
else if (prob < 75)
return Answers.LATER; // 15%
else if (prob < 98)
return Answers.SOON; // 13%
else
return Answers.NEVER; // 2%
}
}
class AskMe {
static void answer(Answers result) {
switch(result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}

Conclusion:
Enums are a powerful and versatile feature in Java that provides a concise and expressive way to define a set of constant values. By understanding the syntax, features, and examples discussed in this article, you can

Top interview Question related to enum in Java

  1. How do you declare an enum in Java?
    Answer: To declare an enum in Java, use the enum keyword followed by the name of the enum type. Inside the enum, list the constant values, separated by commas.
  2. What is the purpose of using enums in Java?
    Answer: Enums in Java are used to represent a fixed set of constant values. They provide a way to define your own data type with a restricted set of possible values, making the code more readable, maintainable, and self-explanatory.
  3. Can an enum have constructors and methods?
    Answer: Yes, an enum in Java can have constructors and methods. This allows you to associate additional information and behaviors with each enum value.
  4. How do you access individual enum values in Java?
    Answer: Individual enum values can be accessed using the dot notation, similar to accessing static fields of a class. Enum values are constants, and you can compare them using the == operator.
  5. Can you override methods in an enum?
    Answer: Yes, you can override methods in an enum. Each enum value can have its own implementation of methods defined in the enum.
  6. How do you compare enum values in Java?
    Answer: Enum values can be compared using the == operator. Enums are reference types, and the == operator compares references to check for equality.
  7. Can enums have additional fields apart from the constant values?
    Answer: Yes, enums in Java can have additional fields apart from the constant values. This allows you to associate extra information with each enum value.
  8. How do you iterate over all the values of an enum?
    Answer: You can iterate over all the values of an enum by using the values() method provided by the enum class. This method returns an array containing all the enum values.
  9. Can enums implement interfaces in Java?
    Answer: Yes, enums in Java can implement interfaces. This allows you to define methods that all enum constants must implement.
  10. How are enums different from regular classes in Java?
    Answer: Enums in Java are similar to regular classes, but they have a fixed set of instances (enum constants) defined at compile-time. Enums cannot be instantiated using the new keyword, and they are implicitly final and static.
  11. Can you use enums in switch statements? How?
    Answer: Yes, enums can be used in switch statements in Java. You can switch on enum values directly, eliminating the need for multiple if-else statements.
  12. What are the benefits of using enums in switch statements?
    Answer: Using enums in switch statements enhances code readability, reduces the chances of errors, and ensures that all possible enum values are handled.
  13. How can you define custom behavior for each enum value?
    Answer: Custom behavior can be defined for each enum value by adding methods to the enum class and implementing them differently for each enum constant.
  14. Can you define abstract methods in enums?
    Answer: Yes, abstract methods can be defined in enums. Each enum constant can provide its own implementation for the abstract method.
  15. How can you convert a string to an enum value in Java?
    Answer: You can convert a string to an enum value in Java by using the valueOf() method provided by the enum class. This method returns the corresponding enum constant for the given string.
  16. How can you retrieve the name or ordinal value of an enum constant?
    Answer: The name of an enum constant can be retrieved using the name() method, and the ordinal value can be retrieved using the ordinal() method.
  17. Can enums be used as keys in a Map collection?
    Answer: Yes, enums can be used as keys in a Map collection. Enums provide unique and constant values, making them suitable for use as keys
  1. Can you serialize and deserialize enums in Java?
    Answer: Yes, enums in Java can be serialized and deserialized. Enum constants are serialized as their names.
  2. Can enums be used in a multi-threaded environment?
    Answer: Enums in Java are inherently thread-safe and can be safely used in a multi-threaded environment.
  3. How does Java ensure type safety with enums?
    Answer: Java ensures type safety with enums by restricting the possible values to a predefined set. The compiler performs type checks to ensure that only valid enum values are used.

FAQs

What is an enum in Java?

An enum in Java is a special data type used to define a set of named constant values. It allows you to create your own data type with a restricted set of possible values.

How do I declare an enum in Java?

To declare an enum in Java, use the enum keyword followed by the name of the enum type. Inside the enum, list the constant values, separated by commas.

Can an enum have methods and fields?

Yes, an enum in Java can have fields, constructors, and methods. This allows you to associate additional information and behaviors with each enum value.

How do I access enum values?

You can access enum values using the dot notation, similar to accessing static fields of a class. Enum values are constants, and you can compare them using the == operator.

Can I use enums in switch statements?

Yes, enums work well with switch statements. You can switch on enum values directly, eliminating the need for multiple if-else statements.

Can I override methods in enum constants?

Yes, you can override methods in enum constants. Each enum value can have its own implementation of methods defined in the enum.

Can I iterate over enum values?

Yes, you can iterate over enum values using the values() method provided by the enum class. This method returns an array of all the enum values.

Can enums implement interfaces in Java?

Yes, enums in Java can implement interfaces. This allows you to define methods that all enum constants must implement.

Can I compare enums in Java?

Yes, you can compare enums in Java using the == operator. Enums are reference types, and the == operator compares references to check for equality.

Leave a Comment