How to Define and Use Constants in Salesforce Apex Classes

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:

Use Final to define constant in Salesforce Apex

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, we will define the constant values for the fields with different data types.

public class ConstantsNumber {
    public static final String ORGANIZATION_NAME = 'Amazon';
    public static final Integer MAX_COUPONS = 5;
    public static final Decimal DISCOUNT_RATE = 0.10;

    public static void displayConstants() {
        System.debug('Organization Name: ' + ORGANIZATION_NAME);
        System.debug('Max number of coupons: ' + MAX_COUPONS);
        System.debug('Discount Rate: ' + DISCOUNT_RATE);
    }
}

Output:

Define Constant in Salesforce Apex Class

Scenario 2:

Let’s take another scenario in an order management system where each order has a standard shipping fee of $10. Instead of defining this fee in different parts of the code, we define it as a constant.

public class OrderHelper {
    public static final Decimal STANDARD_SHIPPING_FEE = 10.00;
    
    public static Decimal calculateTotalWithShipping(Decimal orderAmount) {
        Decimal totalAmount = orderAmount + STANDARD_SHIPPING_FEE;
        return totalAmount;
    }
}

In the above code, STANDARD_SHIPPING_FEE is defined as a constant. The final keyword ensures that the value cannot be modified.

Now, we will use the above method and call it through the Apex anonymous window.

Decimal orderAmount = 150.00;
Decimal totalWithShipping = OrderHelper.calculateTotalWithShipping(orderAmount);
System.debug('Total Amount with Shipping: ' + totalWithShipping);

After executing the anonymous code, you will see that the constant shipping value is added to the order amount.

Output:

Use Constants in Salesforce Apex

This way, we can define and use the constants in Salesforce Apex Classes using the ‘final’ keyword.

Conclusion

In this Salesforce tutorial, we learned about Constants in Salesforce and how to define constant variables in Apex. Then, we defined and used constants in Salesforce Apex classes using the final keyword.

By now, you might have understood the constants in Salesforce Apex and declared them using the final keyword. Using constants in your Apex code can prevent errors and make the codebase easier to understand and work with.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.