Explain Enums in Java and its uses with example

Enums in Java

Enums in Java: In Java, an enum (short for “enumeration”) is a special data type that represents a group of constants. Enums are used to define a collection of constants that are related to each other, providing a type-safe way to work with a fixed set of values. This can make your code more readable and less error-prone.

Uses of Enums in Java

  • Defining Constants: Enums provide a way to define a set of named constants.
  • Type Safety: Enums help ensure that variables are assigned only predefined values, improving type safety.
  • Switch Statements: Enums can be used in switch statements, making the code more readable.
  • Methods and Fields: Enums can have methods and fields, allowing for more complex operations and state within each enum constant.
  • Singleton Pattern: Enums can be used to implement the Singleton pattern in a concise and thread-safe manner.

Example

Here’s a simple example of how to define and use an enum in Java:

// Define the enum
public enum Day {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
}

// Use the enum in a class
public class EnumExample {
    public static void main(String[] args) {
        Day today = Day.MONDAY;

        // Print the value
        System.out.println("Today is " + today);

        // Use in a switch statement
        switch (today) {
            case MONDAY:
                System.out.println("Start of the work week.");
                break;
            case FRIDAY:
                System.out.println("End of the work week.");
                break;
            case SUNDAY:
                System.out.println("Weekend!");
                break;
            default:
                System.out.println("Midweek.");
                break;
        }
    }
}

Advanced Example of Enums in Java

Enums can also contain fields, constructors, and methods. Here’s a more advanced example:

public enum Planet {
    MERCURY(3.303e+23, 2.4397e6),
    VENUS(4.869e+24, 6.0518e6),
    EARTH(5.976e+24, 6.37814e6),
    MARS(6.421e+23, 3.3972e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public double mass() {
        return mass;
    }

    public double radius() {
        return radius;
    }

    // Universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }

    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }

    public static void main(String[] args) {
        double earthWeight = 75;
        double mass = earthWeight / EARTH.surfaceGravity();
        for (Planet p : Planet.values()) {
            System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass));
        }
    }
}

In this example:

  • The Planet enum has fields for mass and radius.
  • It has a constructor to initialize these fields.
  • It includes methods to calculate surface gravity and surface weight.
  • The main method calculates and prints your weight on each planet.

Enums in Java are powerful tools that can simplify the handling of constant values and provide a clearer, type-safe approach to managing fixed sets of data.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *