Apex - if statement


Advertisements

An if statement consists of a Boolean expression followed by one or more statements.

Syntax

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

If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) will be executed.

Flow Diagram

if statement

Example

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 is an implementation of this.

//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');
}

As 'Glenmarkone' is a premium customer so the if block will be executed based on the condition.

apex_decision_making.htm
Advertisements