Up to now your code has run every line from top to bottom, in order. An if statement changes that. It lets your program make a decision: run a block of code only when a condition is true, and skip it otherwise.
An if statement has a condition inside parentheses and a block of code inside curly braces:
Integer temperature = 105;
if (temperature > 100) {
System.debug('It is very hot today.');
}
The condition temperature > 100 is a Boolean expression. When it is true, the code inside the braces runs. When it is false, that code is skipped and the program continues after the closing brace.
Any expression that produces true or false can be a condition. You can compare values, or use a Boolean variable directly:
Boolean isWeekend = true;
if (isWeekend) {
System.debug('Time to relax.');
}
Only the block inside the braces is conditional. Lines after the closing brace always run, no matter what the condition was:
Integer balance = 50;
if (balance < 100) {
balance = balance + 10; // runs only when balance is under 100
}
System.debug(balance); // this line always runs
if (x > 0); creates an empty block and the following braces always run.== to compare inside a condition, never a single =, which is assignment.An if statement is the foundation of every decision your code will ever make.