Back to Enum
Q1Question 1 of 2

What is an enum and how is it different from constants?

Key Concepts
  • An enum is a special class with a fixed set of named instances, created at class load time
  • Enums are type-safe: you cannot pass an invalid value where an enum is expected
  • Each enum constant is a singleton object – == comparison is safe and preferred over .equals()
  • Enums can have fields, constructors, and methods – they are full classes, not just int constants
  • EnumSet and EnumMap are optimized collections backed by bitmasks – extremely fast
  • Use enum instead of int constants or String constants for any fixed set of values

Definition

An enum is a class with a fixed set of named singleton instances. It is type-safe, can have fields and methods, and is the correct replacement for int or String constants.

Enum basics:

  • Fixed set of instances. enum AccountType { SAVINGS, CURRENT, LOAN } creates exactly three instances.
  • Type-safe. A method accepting AccountType cannot receive an invalid value. With int constants, any int could be passed.
  • Full classes. Enums can have fields, constructors, and methods. Each constant can carry data.
  • Singletons. Each constant is one shared object. == is safe for comparison.

A bank's account type dropdown has exactly three options: Savings, Current, Loan. With int constants (1, 2, 3), nothing stops someone from passing 99. With an enum, only the three defined values exist. The form itself enforces the constraint.

Understanding the Concepts

How do you define and use an enum?

JAVA
public enum AccountType {
    SAVINGS, CURRENT, LOAN
}

public class Account {
    private AccountType type;

    public Account(AccountType type) {
        this.type = type;  // can only be SAVINGS, CURRENT, or LOAN
    }
}

Account a = new Account(AccountType.SAVINGS);
// Account b = new Account(99);  // COMPILE ERROR: type mismatch

Why not use int constants?

JAVA
// BAD: int constants
public static final int SAVINGS = 1;
public static final int CURRENT = 2;
public static final int LOAN = 3;

public void process(int accountType) {
    // Nothing stops: process(99) or process(-1)
}

// GOOD: enum
public void process(AccountType type) {
    // Only SAVINGS, CURRENT, LOAN are possible
}

How do you add fields and methods to an enum?

JAVA
public enum AccountType {
    SAVINGS("Savings Account", 4.0),
    CURRENT("Current Account", 0.0),
    LOAN("Loan Account", 8.5);

    private final String displayName;
    private final double defaultRate;

    // Constructor: called once per constant at class load time
    AccountType(String displayName, double defaultRate) {
        this.displayName = displayName;
        this.defaultRate = defaultRate;
    }

    public String getDisplayName() { return displayName; }
    public double getDefaultRate() { return defaultRate; }
}

System.out.println(AccountType.SAVINGS.getDisplayName());  // "Savings Account"
System.out.println(AccountType.LOAN.getDefaultRate());      // 8.5

How do you use enum in switch?

JAVA
AccountType type = AccountType.SAVINGS;

// Classic switch
switch (type) {
    case SAVINGS: System.out.println("4% interest"); break;
    case CURRENT: System.out.println("No interest"); break;
    case LOAN:    System.out.println("8.5% EMI"); break;
}

// Switch expression (Java 14+)
String desc = switch (type) {
    case SAVINGS -> "4% interest";
    case CURRENT -> "No interest";
    case LOAN    -> "8.5% EMI";
};

How do you compare enums?

JAVA
AccountType a = AccountType.SAVINGS;
AccountType b = AccountType.SAVINGS;

// == is correct and preferred for enums
System.out.println(a == b);       // true (singletons)
System.out.println(a.equals(b));  // true (also works)

// == is null-safe
AccountType c = null;
System.out.println(c == AccountType.SAVINGS);  // false (no NPE)
// c.equals(AccountType.SAVINGS)               // NPE!

What are EnumSet and EnumMap?

JAVA
// EnumSet: backed by a bitmask – extremely fast
EnumSet<AccountType> interestBearing = EnumSet.of(AccountType.SAVINGS, AccountType.LOAN);
System.out.println(interestBearing.contains(AccountType.CURRENT));  // false

// EnumMap: backed by an array indexed by ordinal – fast and memory-efficient
EnumMap<AccountType, BigDecimal> rates = new EnumMap<>(AccountType.class);
rates.put(AccountType.SAVINGS, new BigDecimal("4.0"));
rates.put(AccountType.LOAN, new BigDecimal("8.5"));

What are common mistakes?

  • Using String constants instead of enum. "SAVINGS" can be misspelled. AccountType.SAVINGS cannot.
  • Using .equals() instead of ==. Both work, but == is null-safe and faster.
  • Forgetting that enum constructors are private. You cannot write new AccountType(...) outside the enum.

What should a senior engineer know?

  • Enums implement Serializable. They survive serialization correctly – the JVM returns the existing singleton.
  • Enums can implement interfaces. enum AccountType implements Displayable { ... }.
  • Abstract methods on enums force each constant to provide an implementation: each constant becomes an anonymous class.
  • JPA @Enumerated maps enums to database columns: @Enumerated(EnumType.STRING) stores the name, EnumType.ORDINAL stores the position (fragile, avoid).

Visual Overview

DIAGRAM
  enum AccountType { SAVINGS, CURRENT, LOAN }
    │
    ▼
  Three singleton objects created at class load:
    AccountType.SAVINGS  (ordinal 0)
    AccountType.CURRENT  (ordinal 1)
    AccountType.LOAN     (ordinal 2)

  Type safety:
    process(AccountType.SAVINGS)  → OK
    process(99)                    → COMPILE ERROR

  Comparison:
    == is correct (singletons), null-safe, fast
    .equals() also works but == is preferred

  Collections:
    EnumSet  → bitmask, O(1) contains
    EnumMap  → array, O(1) get/put

Key Takeaway

An enum is a special class with a fixed set of named singleton instances. It is type-safe: only the defined values can be used, unlike int or String constants where any value could be passed. Enums can carry fields, constructors, and methods, making them much more powerful than simple constants.

Compare enums with == (not .equals()) because each constant is a singleton. Use EnumSet and EnumMap for collections of enums – they are backed by bitmasks and arrays, making them the fastest collection types in Java.

In banking, use enums for account types, transaction statuses, currency codes, and any other fixed set of values. Map them to database columns with @Enumerated(EnumType.STRING).

One sentence to remember: an enum is a type-safe, singleton-based class for fixed value sets – use == to compare, EnumSet/EnumMap for collections, and never int constants.

---

Share
Use ← → arrow keys to navigate