Sometimes one decision leads to another. Once you know a first condition is true, you may need to ask a second question before you can act. You can place an if statement inside another if statement. This is called nesting.
The inner if only runs when the outer condition is true:
Boolean isLoggedIn = true;
Boolean isAdmin = true;
if (isLoggedIn) {
if (isAdmin) {
System.debug('Show the admin dashboard.');
} else {
System.debug('Show the normal dashboard.');
}
}
Here the code never checks isAdmin unless the user is logged in. The inner decision is nested inside the outer one.
An outer if / else can have completely different logic in each branch, including more conditionals:
Integer age = 30;
Boolean isMember = false;
if (age < 13) {
System.debug('Child price');
} else {
if (isMember) {
System.debug('Member price');
} else {
System.debug('Standard price');
}
}
Nesting is powerful, but deeply nested if statements become hard to read. Two levels are usually fine. When you find yourself nesting three or four levels deep, it is often clearer to combine conditions with logical operators or use an else if chain instead.
Real decisions often depend on more than one factor. Nested conditionals let you handle a first factor, then refine the outcome based on a second. Start with the broadest question on the outside and narrow down as you go in.