Blocks and Compound Statements in Java
The if statement takes the form if ( boolean-expression ) statement-1 else statement-2.
Try it: if / elif / else
How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).
How it works
- Python evaluates the if condition first.
- If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
- If none is True, the else branch runs.
- and stops at the first False, or stops at the first True — the right side may never be evaluated.
Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.
Loading the simulation…
A Decision the Program Must Make
Programs constantly face decisions. A payment either goes through or it does not. A number is either negative or it is not. Java handles decisions like these with branching statements, and the if statement is the first of the two branching statements the language provides.
Before reading any syntax, try to picture the situation as a question the program asks: given a condition, which of two actions should run? Keep that question in mind. The syntax is simply a precise way of writing it down.
As you read this article, follow one decision step by step. Decide for yourself which part of the statement controls the choice and which parts actually execute. The traces in this article will let you check that reasoning against what the program really does.
The General Form of an if Statement
The source gives the if statement as a general template rather than as a complete program. The angle brackets mark placeholders: each one stands for something you fill in with real code. The template has three slots that matter for the syntax, plus a keyword that introduces the second path.
Template: if ( boolean-expression ) statement-1 else statement-2. Read it from left to right. The keyword if comes first, followed by a boolean expression inside parentheses. The boolean expression is the condition, and it evaluates to either true or false. The statement that follows the parentheses is statement-1. If the optional else part is present, it consists of the word else and the statement that follows it, which is statement-2.
The template is therefore a single construction with two possible outcomes, not two separate statements placed side by side. Each part has a specific job, and understanding those jobs separately makes it much easier to read unfamiliar code and to find the source of a bug.
The if Statement as a Two-Way Branch
The if statement is called a two-way branch because the boolean expression selects one of two paths. The expression is evaluated first. If it yields true, statement-1 is taken. If an else part exists and the expression yields false, statement-2 is taken instead. Only one of the two paths runs for any given evaluation.
The diagram is a map of the decision, read from the top. The program reaches the if statement and evaluates the boolean expression. The result selects one path. Whichever path runs, the program then continues with the statement that follows the whole if statement. That is how the two paths rejoin.
Tracing One Decision Step by Step
Take a concrete case. A program stores a test score and decides whether to print Pass or Fail. Trace it before reading the explanation: which line prints when score is 45, and what happens to the other line?
int score = 45;
if (score >= 60)
System.out.println("Pass");
else
System.out.println("Fail");
System.out.println("Done");- 1Line 1 stores 45 in score.
- 2Line 2 evaluates the boolean expression score >= 60. Since 45 is not at least 60, it yields false.
- 3Because the expression is false, statement-1 (the Pass print) is skipped.
- 4The else part is present, so statement-2 (the Fail print) runs.
- 5Line 6 is after the whole if statement, so it runs regardless of which branch was taken.
- score is assigned the value 45
- The boolean expression score >= 60 evaluates to false
- statement-1 is skipped and the else part's statement-2 runs
Fail
DoneThe trace shows the two-way branch in action. The false result sent control to statement-2 and away from statement-1. The Done line is not part of either branch, so it runs in every case.
When There Is No else Part
Many decisions only need one action. If the condition is false, the program should simply carry on. Because the else part can be omitted, the if statement handles this case directly. The statement then consists of the if keyword, the parenthesized boolean expression, and statement-1.
What do you think happens?
Before reading the answer, predict the output of this code when the value of x is -3.
Reveal answer
done
The boolean expression x > 0 is false, so statement-1 (the print of positive) is skipped. There is no else part, so the false result just moves on to the next statement, which prints done.
done- No else part is present, so the if statement has only statement-1
- A false condition skips statement-1 and nothing else happens inside the statement
Grouping Statements with Blocks
A single statement is often not enough for a real decision. You might need to update several variables or print several messages when a condition holds. The source states that, as usual, the statements inside an if statement can be blocks. A block lets you place several statements where the grammar expects one.
In Java, a block is written between curly braces. A block used as statement-1 groups several statements into one branch, so all of them run together when the condition is true, and all of them are skipped together when it is false. The whole block is still one unit inside the if statement, and it can be used as statement-2 in the same way.
Withdrawal approved
Remaining: 30- The curly braces form one block used as statement-1
- Both the assignment and the first print run together because they are inside the block
- The braces are what let several statements sit where the grammar expects one
Mistakes Beginners Make with if Statements
Common mistake Assuming a second statement under an if is part of the if
What it looks likeif (x > 0) System.out.println("positive"); System.out.println("done");Why it failsWithout braces, statement-1 is only the single statement directly after the parentheses. The second print is a separate statement that runs every time.
Do this insteadWrap the statements in a block with curly braces when all of them should run only under the condition.
Common mistake Expecting a statement to run when the condition is false and there is no else part
What it looks likeint x = -3; if (x > 0) System.out.println("positive");Why it failsA false result skips statement-1 entirely. With no else part, there is no alternative statement to run.
Do this insteadCheck whether the action belongs in an else part, or whether the program is supposed to continue without doing anything.
Common mistake Treating the if and the else as two independent statements
Why it failsThe template is a single construction. The else part belongs to the same if statement and is chosen by the same boolean expression.
Do this insteadRead the if and its else as one decision with two outcomes.
Locating an Unexpected Result
When a program produces a result you did not expect, an if statement is a common place to look. Work through these questions in order.
- 1Ask which path the program actually took: statement-1 or statement-2, or neither if there is no else part.
- 2Check the boolean expression. Did it evaluate to the value you assumed?
- 3If the expression was right and the wrong statement ran, check whether the statements were placed in the correct slots, including whether a block was needed.
- 4If you expected a statement to run when no else part exists, remember that a false result skips statement-1 entirely.
Practice Tracing an if Statement
Given int temp = 18; followed by if (temp < 10) { System.out.println("Cold"); } else { System.out.println("Mild"); System.out.println("Check the forecast"); } and then System.out.println("End");, write the exact output. Identify which part of the if runs, and which statement was skipped.
Hints
- Evaluate temp < 10 first. Is 18 less than 10?
- The else part is present, so statement-2 is the block with both Mild and Check the forecast.
- The End line sits after the whole if statement.
Key Takeaways
- The if statement takes the form if ( boolean-expression ) statement-1, with an optional else part followed by statement-2.
- It is a two-way branch: the boolean expression evaluates to true or false, and that result selects which one path runs.
- When there is no else part, a false result skips statement-1 and the program continues with the statement after the if.
- The statements inside an if statement can be blocks written between curly braces, so several statements can act as one branch.
- When a result is unexpected, trace which path ran, check the boolean expression's value, and confirm which statements were placed in which slot.