Constants in Salesforce Apex

Constants in Salesforce Apex

On January 15, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Constants in Salesforce Apex

Table of Contents

What are Apex constants?

Constants in Salesforce Apex are fixed values that do not change during the execution of a program. They are defined using the final keyword, which means once a constant is assigned a value, it cannot be altered. Constants are useful when you want to ensure that specific values remain unchanged throughout your code, maintaining consistency and preventing accidental modification of values that are meant to be static.

In Apex, you declare a constant by specifying the data type, followed by the final keyword, and then the variable name. You typically assign a value to a constant at the time of its declaration. For instance, if you want to define a constant for the maximum number of records that can be processed in a batch, you might write something like private static final Integer MAX_RECORDS = 200; . This statement creates a constant named MAX_RECORDS with a value of 200, and this value cannot be changed throughout the program.

For those looking for Salesforce learning, CRS Info Solutions provides an extensive Salesforce training program designed to enhance your skills and career opportunities. Explore our Salesforce training in India to gain practical, hands-on experience. Our training covers all essential aspects of Salesforce, ensuring comprehensive learning. With expert instructors and a detailed curriculum, CRS Info Solutions is committed to your success in the Salesforce ecosystem with our Career Building program. Whether you are a beginner or looking to advance your skills, they offer the guidance and resources you need. Enroll for free demo today!

The final keyword indicates that the variable can only be initialized once, either directly, or with a static initializer method. 

For example:

public class myCls {
    static final Integer PRIVATE_INT_CONST = 200;
    static final Integer PRIVATE_INT_CONST2;

    public static Integer calculate() {
        return 2 + 7;

    static {
        PRIVATE_INT_CONST2 = calculate();

Here’s a simple example of how you can define and use constants in Salesforce Apex:

public class ConstantsDemo {
    // Define a constant for the maximum size
    private static final Integer MAX_SIZE = 100;
    public void printMaxSize() {
        // MAX_SIZE is used within a method
        System.debug('The maximum size is: ' + MAX_SIZE);

n this example, ConstantsDemo is a class that contains a constant named MAX_SIZE . The MAX_SIZE constant is defined with the private static final keywords, indicating that it’s a private constant accessible only within this class, and its value cannot be changed after initialization. The value of MAX_SIZE is set to 100.

The printMaxSize method demonstrates how you can use the MAX_SIZE constant within the class. It prints the value of the MAX_SIZE constant to the debug log. Since MAX_SIZE is a constant, its value will remain 100 throughout the program, and any attempt to change its value will result in a compilation error.

Online Shopping Application Example using Constants

Let’s see another constants example that is being used in a real world application, let’s say which used in online shopping application.

In an online shopping application, constants can be used to represent values that are important for business logic and that do not change over time. For example, constants could be used to define tax rates, shipping costs, or discount thresholds. Below is an example of how constants might be used in a Salesforce Apex class for an online shopping application to define the tax rate and free shipping threshold:

public class ShoppingCart {
    // Constants
    private static final Double TAX_RATE = 0.08; // 8% tax rate
    private static final Double FREE_SHIPPING_THRESHOLD = 50.00; // Free shipping for orders over $50
    // Method to calculate the total cost including tax
    public static Double calculateTotalCost(Double subtotal) {
        Double tax = subtotal * TAX_RATE;
        return subtotal + tax;
    // Method to determine if the order is eligible for free shipping
    public static Boolean isEligibleForFreeShipping(Double subtotal) {
        return subtotal >= FREE_SHIPPING_THRESHOLD;
    // Other methods related to the shopping cart...

In this example:

  • TAX_RATE is a constant representing the tax rate applied to purchases. This is particularly useful if the tax rate is referenced in multiple places throughout the application, ensuring that any changes to the rate only need to be made in one location.
  • FREE_SHIPPING_THRESHOLD is a constant representing the minimum subtotal required for an order to be eligible for free shipping. Similar to TAX_RATE , this centralizes the value, making the code more maintainable.

Aviation Crew Management Application Example

In an aviation crew application, constants can be used to define values that are critical for flight operations and need to be consistent and error-free throughout the application. For example, a constant might be used to represent the maximum number of crew members allowed on a certain type of aircraft. This ensures that the application always enforces the same crew size limit, maintaining safety and compliance with aviation regulations.

Here’s how such a constant might be defined and used in Apex:

public class CrewManagement {
    // Define a constant for the maximum number of crew members on a type of aircraft
    private static final Integer MAX_CREW_MEMBERS = 10;

    public void assignCrew(List<CrewMember> crewList, Aircraft aircraft) {
        // Check if the number of crew members does not exceed the maximum limit
        if (crewList.size() > MAX_CREW_MEMBERS) {
            throw new CrewAssignmentException('Cannot assign more than ' + MAX_CREW_MEMBERS + ' crew members to ' + aircraft.getName());

        // Code to assign the crew members to the aircraft
        // ...
    // Rest of the class implementation
    // ...

In this example, MAX_CREW_MEMBERS is a constant representing the maximum number of crew members allowed. It’s used in the assignCrew method to ensure that the crew assignment does not exceed this limit. By using a constant, the number is defined in one place, making the code easier to understand and maintain. If the regulation changes, you only need to update the constant’s value in one location, and the change will be reflected throughout the application.

Frequently Asked Questions

Can you explain the purpose of using constants in Apex, and how do you declare them?

In Apex, constants are used to store values that should not change throughout the execution of the program. They bring stability and predictability to the code by ensuring that certain values remain fixed, which is particularly important in applications where certain parameters are critical and should not be altered accidentally.

To declare a constant in Apex, you use the final keyword along with the data type and the variable name. For instance, you might declare a constant integer like this: private static final Integer MAX_USERS = 100; . This line of code sets MAX_USERS as a constant with a value of 100, and this value won’t change, ensuring that parts of your code that rely on this number can operate consistently.

Using constants is a good practice because it makes your code more readable and maintainable. When someone reads your code and sees a constant, they immediately know this value is crucial and it’s been set deliberately to remain constant throughout the application. This clarity helps prevent errors and makes the codebase easier to understand and work with.

How does the final keyword work in Apex, and what happens if you try to modify a constant after it’s been initialized?

The final keyword in Apex is used to declare constants, meaning once a value is assigned to a variable using final , it cannot be changed later. When you declare a variable as final, you are essentially making a contract that this variable will hold the same value throughout its lifecycle in the application.

If you try to modify a constant after it’s been initialized, Apex will throw a compilation error. This is because the whole purpose of a constant is to remain constant, ensuring that important values in your application don’t get altered unexpectedly. The final keyword enforces this rule, making your code more robust and predictable.

For example, if you declare final Integer MAX_LOGIN_ATTEMPTS = 3; and later in the code, you try to reassign it like MAX_LOGIN_ATTEMPTS = 4; , the compiler won’t allow this and will generate an error. This ensures that the value of MAX_LOGIN_ATTEMPTS remains 3 throughout the application, preventing any accidental changes that could lead to potential issues or inconsistencies in your code logic.

Can you provide an example of a scenario in Apex where it is essential to use constants, and explain why?

Constants in Apex are particularly essential in scenarios where you need to ensure that certain values remain unchanged to maintain the integrity of your application’s logic. One such scenario could be in managing application configuration settings.

For example, suppose you’re developing a complex application that interacts with an external API, and this API allows a maximum of 1000 requests per hour. You would declare this as a constant in your Apex code, something like private static final Integer MAX_API_REQUESTS_PER_HOUR = 1000; . This constant would be used throughout your code to ensure that your application does not exceed the API’s rate limit.

Using a constant in this scenario is crucial because the number of API requests is a critical parameter for the application’s interaction with the external service. If this value were inadvertently changed, it could lead to the API service denying requests, which would disrupt the functionality of your application. By using a constant, you safeguard this value, making your application’s behavior predictable and stable, and you also make your code more readable and maintainable, as it’s clear that this value is a fixed configuration and not something that should be modified.

Elevate your professional game with CRS Info Solutions’ Salesforce course, where over 15 years of industry expertise shapes your learning. Dive deep into courses filled with real-world projects, daily pointers for acing interviews, and a mentorship program that steers you towards certification success.

CRS Info Solutions offers a comprehensive and dynamic Salesforce course for beginners career building program for beginners, covering admin, developer, and LWC concepts. This course features immersive real-time projects, interactive hands-on learning, detailed daily notes, essential interview questions, thorough certification preparation, and strategic job prep guidance. Join their inspiring free demo to embark on an exciting Salesforce journey with expert mentorship and unlock your full potential in the Salesforce ecosystem. Enroll for a free demo today!

Read the previous one Salesforce Apex Arrays and next one.

Comments are closed.