In Salesforce Apex, constants store values that should not change throughout the program’s execution. They bring stability and predictability to the code by ensuring that specific values remain fixed.
This is particularly important in applications with specific parameters that should not be altered.
In this Salesforce tutorial, we will learn how to define and use constants in Salesforce Apex classes.
What are Apex Constants in Salesforce?
In Salesforce Apex, Constants are fixed values that remain unchanged throughout code execution. They are defined using the final keyword, which means a value is assigned to the constant and cannot be altered.
They are generally helpful when we want specific values to remain unchanged throughout the code execution. This prevents unnecessary modification of static values.
In Apex, Constants are defined with the specific data types, followed by the final keyword and the variable’s name. Constants are usually given a value when they are declared.
For example, you have to define a constant for the number of records that can be processed in a single Apex batch; you can write it like “private static final Integer GET_RECORDS = 150.”
This will create a constant called GET_RECORDS with a fixed value of 150 that will remain unchanged throughout the code execution.
How does the final keyword work in Apex
In Salesforce Apex, when defining constants, once a value is assigned to a variable using the final keyword, it cannot be changed later. With the final keyword, we declare that this variable will hold the same value throughout the code execution.
If we try to modify a constant after its initialization, Apex will throw a compilation error. This is because the whole purpose of a constant is to ensure that essential values in your application aren’t altered unexpectedly. All this is ensured with the help of a constant keyword final.
Anonymous code of redeclaring the constant variable:
final Integer myConstant = 10;
System.debug('Initial Value: ' + myConstant);
//reassign the constant variable
myConstant = 20;
System.debug('Updated Value: ' + myConstant);
Output:

Define and Use Constants in Salesforce Apex Classes
To define a constant in the apex class, we need to use the final keyword and specify an access modifier such as public, private, or protected. Next, we need to select a data type and assign a value to the constant.
Apex code example for class with constant:
public class ConstantNumber {
private static final Integer Locations = 15;
public void Locations() {
System.debug('The number of locations is: ' + Locations);
}
}
Use case of Constant in Apex Class:
Let’s consider a scenario in which we need to limit the number of discount coupons available on an e-commerce website. Using the constant keyword final