Wednesday, January 25, 2017

Apex - Constants

As in any other programming language, Constants are the variables which do not change their value once declared or assigned a value.

In Apex, Constants are used when we want to define variables which should have constant value throughout the program execution. Apex constants are declared with the keyword 'final'.
Example:
Consider a CustomerOperationClass class and a constant variable regularCustomerDiscount inside it:
public class CustomerOperationClass {
    static final Double regularCustomerDiscount = 0.1;
    static Double finalPrice = 0;
    public static Double provideDiscount (Integer price) {
        //calculate the discount
        finalPrice = price - price*regularCustomerDiscount;
        return finalPrice;
    }
}
To see Output of above class, you have to execute the following code in developer console anonymous window:
Double finalPrice = CustomerOperationClass.provideDiscount(100);
System.debug('finalPrice '+finalPrice);

No comments:

Post a Comment