Salesforce with Ankit

Salesforce beyond the clouds !

Control Statements and Loops

In this article, we will discuss about control statements, their syntax and some examples. Also we will discuss about various loops, syntax and example.

  1. If Statement –
    • If statement takes in Boolean value or an expression returning a boolean value, and if that value is true then code-block will be executed.
    • For example:
      • if ( condition is true ) { //code block will be executed }
  2. If-else Statement –
    • We can extend if statement using the optional else control statement.
    • The else statement provides the block of code to be executed when condition inside if is false.
    • For Example:
      • if ( conditionIsFalse) { //if-statement block }
      • else { else-statement block }
  3. Nested if-else –
    • When we have to use more than one condition, then we can use if-statement followed by else-if statement with optional else statement.
    • For Example:
      • if ( condition 1 ) { //code }
      • else if ( condition 2 ) { //code } ………………………..
      • else if ( condition n ) { //code }
      • else { code }
  4. Ternary-if –
    • Ternary-if statements are single line expressions that assign s value based upon decision made inline.
    • Ternary-if is formed of three parts:
      • variable = booleanExpressionToEvaluate ? outcomeIfTrue : outcomeIfFalse;
    • For Example:
      • x = (p>q) ? 7 : 9 ;
  5. Switch Statements –
    • The switch statements allows you to evaluate a variable and execute a block of code based upon the value of the variable matching definite value.
    • Syntax:
      • switch on variable {
      • when value 1 { code }
      • when value 2 { code } ………………..
      • when value n { code } }

We have covered all control statements in Apex, now we will discuss about various loops in Apex.

  1. Do – While Loop –
    • A do-while loops allows developer to specify block of code that they want to execute whilst a set boolean-condition remains true.
    • Syntax:
      • do { code } while ( condition );
  2. While Loop –
    • While loop evaluates a code block while boolean-condition is met, but unlike do-while in while loop, condition is evaluated before execution of the code.
    • Syntax:
      • while ( condition ) { code }
  3. For Loop –
    • For loops can be constructed in many ways, most familiar format is given below:
      • for ( Integer i = 0 ; i < limit ; i++ ) { code }
    • For lists, following variation of for loop can be used:
      • for ( DataType variableName: List<DataType>) { code }

These all loops are very helpful while coding in Apex, thanks for reading the article till the end, in next article we will discuss about Apex Triggers.

Published by

Leave a comment