Beginner 15 min read

Declaring and Using Enums

By the end of this lesson, you'll be able to:

  • Declare an enum with a list of values
  • Declare a variable of an enum type and assign it a value
  • Compare enum values using ==

Prerequisites: "What Is an Enum?"

Declaring an enum

public enum OrderStatus { PENDING, SHIPPED, DELIVERED, CANCELLED }

This defines a brand-new type, OrderStatus, whose only valid values are the four listed. By convention, enum values are written in ALL_CAPS, similar to the constants from Module 3.

Using it

OrderStatus currentStatus = OrderStatus.PENDING;
System.debug(currentStatus); // PENDING

if (currentStatus == OrderStatus.PENDING) {
    System.debug('Order has not shipped yet.');
}

Values are always accessed with the enum's name first — OrderStatus.PENDING, never just PENDING on its own — and compared with the same == you already know from Module 4.

A real business example: Customer Support

public enum CasePriority { LOW, MEDIUM, HIGH, CRITICAL }

CasePriority ticketPriority = CasePriority.HIGH;
Boolean needsImmediateAttention = ticketPriority == CasePriority.CRITICAL;

A support ticket's priority is exactly the kind of small, fixed set an enum protects — no risk of a rogue 'urgent' or 'Hi-priority' string sneaking past validation.

Common mistakes

  • Forgetting the enum name when referencing a value. currentStatus == PENDING won't compile — it must be currentStatus == OrderStatus.PENDING.
  • Trying to add a value that isn\'t in the list. OrderStatus.REFUNDED doesn\'t exist unless it was added to the enum's declaration — this is the whole point, not a limitation.

Exercise

Declare an enum called LoanStatus with values SUBMITTED, UNDER_REVIEW, APPROVED, and REJECTED. Declare a variable of that type set to UNDER_REVIEW, and debug whether it equals APPROVED.

Show hint

public enum LoanStatus { SUBMITTED, UNDER_REVIEW, APPROVED, REJECTED }

APEX

Declaring and Using Enums Quiz

1. How do you reference a specific enum value?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Declaring an enum is a one-line statement naming its allowed values; using one looks and feels just like working with any other typed variable, complete with == comparisons.