Search Here

Apex - Constants program

you can create constants using the final keyword to define values that should not be changed throughout the execution of your program. Here's an example program demonstrating how to define and use constants in Apex:


public class ConstantsExample {

    // Define a constant for the maximum score

    public final Integer MAX_SCORE = 100;


    public void displayScore(Integer score) {

        if (score > MAX_SCORE) {

            System.debug('Invalid score: exceeds the maximum allowed score.');

        } else {

            System.debug('Score is valid: ' + score);

        }

    }


    public static void main() {

        ConstantsExample example = new ConstantsExample();

        Integer userScore = 95;


        System.debug('Maximum Allowed Score: ' + example.MAX_SCORE);

        example.displayScore(userScore);

    }

}


We create a class ConstantsExample to encapsulate our constant and a method displayScore to demonstrate its usage.

Inside the class, we define a constant MAX_SCORE with the final keyword, and we set it to 100. This means that MAX_SCORE cannot be modified after it is assigned a value.

The displayScore method checks if a user's score exceeds the maximum allowed score (the constant) and provides feedback accordingly.

In the main method, we create an instance of the ConstantsExample class and display the maximum allowed score and a user's score using the displayScore method.



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.