The if-else Statement 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…
Decisions a 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, because the syntax is simply a precise way of writing it down.
What do you think happens?
In the code below, score is 45. Which line gets printed?
Reveal answer
Fail
The boolean expression score >= 60 is false for 45, so the statement after the else runs and the statement after the if is skipped. The trace in the next section follows this step by step.
Tracing a Single Decision
Here is a small program that makes one decision. Before reading the explanation, follow the program yourself: find the value of score, evaluate the condition, and decide which line runs.
int score = 45;
if (score >= 60)
System.out.println("Pass");
else
System.out.println("Fail");- 1Line 1 stores 45 in score.
- 2Line 2 evaluates the boolean expression score >= 60. For 45 this is false.
- 3Because the expression is false, the statement after the if (the Pass print) is skipped.
- 4The else part is present, so its statement runs, which prints Fail.
- 5The program then continues with whatever follows the if-else. Nothing else follows here, so it ends.
- score is set to 45 before the decision
- The boolean expression score >= 60 is evaluated and yields false
- The false result selects the statement after else
FailThe diagram is a map of the same decision. The condition is checked first. Its result selects one path, the Pass print is skipped, and only the Fail print executes. The outcome is traceable to one place: the boolean expression evaluated to false for this input.
Parts of the if-else Template
The source gives the if statement as a general template rather than a complete program. The template takes the form if ( boolean-expression ) statement-1 else statement-2. The angle-bracket style names are placeholders: each one stands for something you fill in with real code.
Read the template from left to right. The keyword if comes first, followed by a boolean expression inside parentheses. The boolean expression is the condition: 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.
Why It Is a Two-Way Branch
The if statement is described as a two-way branch because the boolean expression decides which statement runs, and there are exactly two possible destinations. When the expression yields true, statement-1 is taken. When an else part exists and the expression yields false, statement-2 is taken.
The map also shows how the two paths meet again. Whichever statement ran, the program then continues with the code that follows the whole if-else. The decision selects a path for that one step, and the program then carries on as a single sequence.
Omitting the 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 shorter form consists of the if keyword, the parenthesized boolean expression, and statement-1.
int temperature = 12;
if (temperature < 0)
System.out.println("Freezing");
System.out.println("Checked temperature");- 1temperature is set to 12.
- 2The boolean expression temperature < 0 is false.
- 3statement-1 (the Freezing print) is skipped, and nothing else happens inside the if statement.
- 4The program continues to the line after the if statement, which prints Checked temperature.
- No else part is written
- The condition is false for 12
- The final print is outside the if statement
Checked temperatureWhen an if statement has no else part and its expression is false, statement-1 is skipped and the program continues with whatever follows the if statement.
Using Blocks for Several Statements
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 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, so a block used as statement-1 or statement-2 groups several statements into one branch.
A block on each branch
Print two messages when score is at least 60, and two different messages otherwise, for score = 45.
- 1Set the input
score is 45, so the condition score >= 60 is false.
- 2Select the branch
The false result selects the else part, so the block after else is the one that runs.
- 3Run the whole block
Both statements inside that block execute in order, because the braces group them as one branch.
- 4Skip the other block
The block after the if keyword is skipped entirely, so neither of its messages prints.
The output is Fail, followed by Try again next term.
Fail
Try again next term- Each branch is a block in curly braces
- The whole block after else runs when the condition is false
Tracing an Unexpected Result
When a program produces a result you did not expect, an if statement is a common place to look. Start by asking which path the program actually took. Then check the boolean expression: did it evaluate to the value you assumed? If the expression was right and the wrong statement ran, check whether the statements sit in the correct slots.
Locating a statement that always runs
The programmer expects big to print only when x is greater than 5. With x = 3, the program prints big anyway. Find where the unexpected output comes from.
- 1Ask which path ran
The output shows that the print statement ran, so the program took the path that executes it.
- 2Check the expression
x > 5 is false for x = 3, so the expression yielded the value the programmer assumed.
- 3Check the slots
A semicolon directly after the parentheses makes statement-1 an empty statement. The false result skips that empty statement.
- 4Find the real culprit
The println on the next line is a separate statement outside the if, so it runs every time.
The bug is the stray semicolon. Removing it makes the println part of the if statement, so nothing prints for x = 3.
big- The semicolon after the parentheses ends the if statement
- println runs as its own statement, not as statement-1
Mistakes That Cause Unexpected Output
Common mistake Placing a semicolon directly after the if condition
What it looks likeif (x > 5); followed by a println on the next lineWhy it failsThe semicolon makes statement-1 an empty statement, so the if controls nothing and the following println always runs.
Do this insteadRemove the semicolon so the intended statement sits directly in the slot after the parentheses.
Common mistake Expecting several statements after an if to be conditional without braces
What it looks likeif (x > 5) println(big); followed by println(done); on the next lineWhy it failsWithout braces, statement-1 is only the single statement right after the parentheses. The second println is outside the if.
Do this insteadWrap every statement that belongs to the branch in curly braces, creating a block.
Common mistake Assuming the else part runs when the condition is true
Why it failsThe statement after else is statement-2, which is taken only when the boolean expression yields false.
Do this insteadRead the condition as selecting statement-1 for true and statement-2 for false.
Common mistake Expecting a statement to run when no else part exists and the condition is false
Why it failsA false result skips statement-1 entirely when there is no else part, and the program continues after the if statement.
Practice Tracing a Branch
Given int temperature = 18; and the statement if (temperature > 25) System.out.println("Warm"); else System.out.println("Cool");, which line is printed, and which statement is skipped? Explain your answer by naming the boolean expression and its value.
Hints
- Identify the boolean expression first and decide whether it is true or false for 18.
- A false result selects the statement after else.
- Name the skipped statement as statement-1 or statement-2 in your explanation.
Key Takeaways
- The if statement takes the form if ( boolean-expression ) statement-1 else statement-2, where the boolean expression evaluates to true or false.
- The if-else is a two-way branch: a true result takes statement-1, and a false result takes statement-2 when an else part exists.
- The else part is optional. When it is omitted and the expression is false, statement-1 is skipped and the program continues after the if statement.
- Statements inside an if or else can be blocks written in curly braces, which groups several statements into one branch.
- To trace an unexpected result, identify the path taken, check the boolean expression's value, and verify that each statement sits in the intended slot.