Apex - if else statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.


if boolean_expression {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */

If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

Flow Diagram

if-else Statement


Suppose, our Chemical company has customers of two categories – Premium and Normal. Based on the customer type, we should provide them discount and other benefits like after sales service and support. Following program shows an implementation of the same.

//Execute this code in Developer Console and see the Output
String customerName = 'Glenmarkone'; //premium customer
Decimal discountRate = 0;
Boolean premiumSupport = false;

if (customerName == 'Glenmarkone') {
   discountRate = 0.1; //when condition is met this block will be executed
   premiumSupport = true;
   System.debug('Special Discount given as Customer is Premium');
}else {
   discountRate = 0.05; //when condition is not met and customer is normal
   premiumSupport = false;
   System.debug('Special Discount Not given as Customer is not Premium');

As 'Glenmarkone' is a premium customer so the if block will be executed based on the condition and in rest of the cases, the else condition will be triggered.

Kickstart Your Career

Get certified by completing the course

Get Started