DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java OOPTopic 57 of 59
←PreviousPrevNextNext→

Java Enums

Introduction to Enums

Enums (enumerations) in Java are special data types that enable a variable to be a set of predefined constants.

Enums improve type safety, make code more readable, and prevent invalid values. They were introduced in Java 5 and are more powerful than traditional enum patterns in other languages.

Basic Enum Declaration

Enums are declared using the 'enum' keyword. Each constant is an instance of the enum type.

Example
// Simple enum declaration
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class BasicEnumExample {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        
        // Using switch statement with enum
        switch(today) {
            case MONDAY:
                System.out.println("Start of work week");
                break;
            case FRIDAY:
                System.out.println("Almost weekend!");
                break;
            default:
                System.out.println("Midweek day");
        }
        
        // Getting all enum values
        System.out.println("\nAll days:");
        for (Day day : Day.values()) {
            System.out.println(day);
        }
    }
}
Output
Start of work week

All days:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Enums with Fields and Methods

Java enums can have fields, constructors, and methods, making them more powerful than simple constant lists.

Example
enum Planet {
    // Enum constants with values
    MERCURY(3.303e+23, 2.4397e6),
    VENUS(4.869e+24, 6.0518e6),
    EARTH(5.976e+24, 6.37814e6),
    MARS(6.421e+23, 3.3972e6),
    JUPITER(1.9e+27, 7.1492e7),
    SATURN(5.688e+26, 6.0268e7),
    URANUS(8.686e+25, 2.5559e7),
    NEPTUNE(1.024e+26, 2.4746e7);
    
    // Fields
    private final double mass;   // in kilograms
    private final double radius; // in meters
    
    // Constructor
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    
    // Methods
    public double getMass() { return mass; }
    public double getRadius() { return radius; }
    
    public double surfaceGravity() {
        final double G = 6.67300E-11; // gravitational constant
        return G * mass / (radius * radius);
    }
    
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}

public class AdvancedEnumExample {
    public static void main(String[] args) {
        double earthWeight = 75; // kg
        
        System.out.println("Weight on different planets:");
        for (Planet p : Planet.values()) {
            System.out.printf("Your weight on %s is %.2f kg%n", 
                            p, p.surfaceWeight(earthWeight));
        }
    }
}
Output
Weight on different planets:
Your weight on MERCURY is 28.32 kg
Your weight on VENUS is 67.97 kg
Your weight on EARTH is 75.00 kg
Your weight on MARS is 28.39 kg
Your weight on JUPITER is 189.34 kg
Your weight on SATURN is 80.14 kg
Your weight on URANUS is 67.97 kg
Your weight on NEPTUNE is 85.24 kg

Enum Methods

MethodDescription
values()Returns an array containing all enum constants
valueOf(String)Returns the enum constant with the specified name
name()Returns the name of the enum constant as a string
ordinal()Returns the position of the enum constant (0-based)
compareTo()Compares this enum with the specified object for order

Enums with Abstract Methods

Enums can have abstract methods, with each constant providing its own implementation.

Example
enum Operation {
    PLUS {
        public double apply(double x, double y) { return x + y; }
    },
    MINUS {
        public double apply(double x, double y) { return x - y; }
    },
    TIMES {
        public double apply(double x, double y) { return x * y; }
    },
    DIVIDE {
        public double apply(double x, double y) { return x / y; }
    };
    
    // Abstract method
    public abstract double apply(double x, double y);
}

public class EnumWithAbstractMethod {
    public static void main(String[] args) {
        double x = 10, y = 5;
        
        for (Operation op : Operation.values()) {
            System.out.printf("%s %.1f and %.1f = %.1f%n", 
                            op, x, y, op.apply(x, y));
        }
    }
}
Output
PLUS 10.0 and 5.0 = 15.0
MINUS 10.0 and 5.0 = 5.0
TIMES 10.0 and 5.0 = 50.0
DIVIDE 10.0 and 5.0 = 2.0

Best Practices

- Use enums instead of integer or string constants for better type safety

- Use enums when you have a fixed set of related constants

- Consider adding methods to enums to make them more useful

- Use the toString() method for user-friendly representations

- Be cautious with ordinal() as it depends on declaration order

Test your knowledge: Java Enums
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java OOPTopic 57 of 59
←PreviousPrevNextNext→