SAVE UP to ₹4999/- OFF On All Salesforce Courses Claim Offer

3

Enums in APEX

Enums in Apex are a unique construct used to define a collection of constants. It is an abstract datatype with values that each take on exactly one of the finite sets of identifiers that you specify.

It provides a clear and concise way to represent a fixed set of values. By using enums, you can make your Apex code more readable, and maintainable. They also ensure values are restricted to predefined options, reducing errors and simplifying decision-making processes in code.

How to Define an Enum?

Enums in Apex are defined using the enum keyword. An enum is a particular data type that enables a variable to be a set of predefined constants. The syntax for defining an enum is straightforward:

public enum Season {
    WINTER,
    SPRING,
    SUMMER,
    FALL
}

Enum Methods

An enum is an abstract data type in which each value can have exactly one of the specified limited set of identifiers. You can create your enum or use one of the built-in enums that Apex provides, such as LoggingLevel. User-defined methods cannot be added to enum values.

All Apex enums, whether user-defined enums or built-in enums have these standard methods:

S.NoFunctionExample
1valuesThis method returns the values of the Enum as a list of the same Enum type.List<Season> seasons = Season.values();System.debug(seasons); // Outputs: (WINTER, SPRING, SUMMER, FALL)
2valueOf(string enumStr)This method converts a specified string to an enum constant value. An exception is thrown if the input string doesn’t match an enum value.Season season = Season.valueOf(‘SUMMER’);System.debug(season); // Outputs: SUMMER
3nameReturns the name of the Enum item as a String.String seasonName = Season.SUMMER.name();System.debug(seasonName); // Outputs: SUMMER
4ordinalReturns the position of the item, as an Integer, in the list of Enum values starting with zero.Integer position = Season.SUMMER.ordinal();System.debug(position); // Outputs: 2 (since SUMMER is the third value, and indexing starts at 0)
Salesforce Developer Training CTA
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Book A 15-Minutes Free Career Counselling Today!