Enums in APEX
Chapter Topics
- Apex Data Types
- Integer Data Type in APEX
- Floating Point Data Type in APEX
- String Data Type in APEX
- Date Datatypes in APEX
- Time and DateTime Data Types in APEX
- Boolean Datatype in Salesforce
- ID & Blob Datatypes in APEX
- What is the Rule of Conversions in Apex?
- Enums in APEX
- sObjects in Salesforce
- Generic sObjects in Salesforce
- Collections in APEX
- Lists in APEX
- List Array Notation in APEX
- Lists Initialization in APEX
- Nested Lists in APEX
- Sets in APEX
- Sets Initialization And Methods
- Maps in APEX
- Map Initialization Methods in APEX
- Operators in Apex and Their Types
- Shorthand Operator
- Equality Operator
- Relational Operators(<,>,<=,>=)
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.No | Function | Example |
1 | valuesThis 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) |
2 | valueOf(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 |
3 | nameReturns the name of the Enum item as a String. | String seasonName = Season.SUMMER.name();System.debug(seasonName); // Outputs: SUMMER |
4 | ordinalReturns 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) |
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.