Notes
Apex supports the usual logical conditions from mathematics:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to a == b
- Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Use the if statement to specify a block of Apex code to be executed if a condition is true.
if (4 > 3) {
System.debug('4 is greater than 3');
}
We can also test variables:
Integer x = 20;
Integer y = 18;
if (x > y) {
System.debug('x is greater than y');
}
Use the else statement to specify a block of code to be executed if the condition is false.
Integer x = 4;
if (x==4) {
System.debug('x is equal to 4');
} else {
System.debug('x is not equal to 4');
}
Use the else if statement to specify a new condition if the first condition is false.
Integer timeNow = 22;
if (timeNow < 10) {
System.debug('Good morning.');
} else if (timeNow < 20) {
System.debug('Good day.');
} else {
System.debug('Good evening.');
}
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:
Integer timeNow = 20;
String result = (timeNow < 18) ? 'Good day.' : 'Good evening.';
System.debug(result);
Examples
Integer score =43;
if(score>90){
System.debug('A+');
}
else if(score>80){
System.debug('A');
}
else if(score>70){
System.debug('B');
}
else if(score>60){
System.debug('C');
}
else if(score>50){
System.debug('D');
}
else{
System.debug('F');
}
More Examples:
Integer x=3;
if(false){
x+=3;
}
else{
x*=3;
}
System.debug(x);