if, else, do, while, for, break, continue

if

if keyword defines a conditional statement, used to determine whether a code block should be executed based on a condition.

Example

Integer i = 1;
if (i > 0) {
    // do something;
}

else

Defines the else portion of an if-else statement, that executes if the initial evaluation is untrue.

Example

Integer x, sign;

if (x==0) {
    sign = 0;
} else {
    sign = 1;
}

while

while keyword executes a block of code repeatedly as long as a particular boolean condition remains true.

Example

Integer count=1;

while (count < 11) {
    System.debug(count);
    count++;
}

do

do keyword defines a do-while loop that executes repeatedly as long as a boolean condition evaluates to true.

Example

Integer count = 1;
do {
System.debug(count);
count++;
}

for

for keyword is used to define a loop. There are three types of for loops.

  1. iteration using a variable
  2. iteration over a list
  3. iteration over a query.

Example

// loop that iterates based on a condition
for (Integer i = 0, j = 0; i < 10; i++) {
	System.debug(i+1);
}

Integer[] myInts = new Integer[]{1,8, 9};
// loop that iterates for each element of an array
for (Integer i : myInts) {
	System.debug(i);
}

String s = 'Acme';
// loop that iterates for each row in the resultset
for (Account a : [SELECT Id, Name,FROM account WHERE Name LIKE :(s+'%')]) {
	// Your code
}

break

break keyword is used to exit the enclosing loop prematurely.

In the following example, break keyword is used to break the while loop prematurely when a specific condition is met.

while(reader.hasNext()) {
	
	if (reader.getEventType() == END) {
		break;
	};
	
	// process
	reader.next();
}

continue

continue keyword skips to the next iteration of the loop. The statements in the loop block after the continue statement are skipped and the execution continues with the loop again.

Example

while (boolean_expression) {
    if (condition) {
        continue;
    }
    // do some work
}