An if statement runs a block of code only when its condition is true, and adding else gives a second block that runs when the condition is false. An else-if chain tests several conditions from top to bottom and runs only the block of the first one that is true, so the order of the conditions can change the result.
Quick check
What does the expression 7 >= 7 evaluate to?Show answerHide answer
It evaluates to
true, because>=means "greater than or equal to" and 7 equals 7.If int n = 9, is n % 2 == 0 true or false?Show answerHide answer
It is
false:9 % 2is 1, not 0, so 9 is odd.An if-else statement has two blocks. How many of them run each time the statement runs?Show answerHide answer
Exactly one: the
ifblock when the condition istrue, theelseblock when it isfalse.
Know these already? Jump to the practice questions
What you'll be able to do
- Identify which branch of an
if,if-elseor else-if chain runs for a given input. - Explain why the order of the conditions in an else-if chain can change the result.
- Determine the output of nested
ifstatements, including anelsewritten without braces. - Choose between separate
ifstatements and one else-if chain for a task.
Key terms
Block
Statements inside a pair of braces, which Java treats as one statement.
- In plain English
- The code fenced off by braces for one branch.
- Don't write
- "The indentation shows which statements belong to the if."
Else-if chain
An if followed by else if parts and an optional final else; only the block of the first true condition runs.
- In plain English
- A list of tests where only the first match counts.
- Don't write
- "Every branch whose condition is true runs."
Nested if
An if statement inside a branch of another if or else, tested only when that branch runs.
- In plain English
- A follow-up question asked only after the first answer.
- Don't write
- "The inner if is tested every time."
How does an if statement decide whether code runs?
An if statement tests a condition, a Boolean expression in parentheses. If it is true, the block after it runs; if it is false, Java skips the block. Either way, execution continues after the block. This is one-way selection: one optional path, called a branch.
int temp = 31;
if (temp > 30)
{
System.out.println("Hot");
}
System.out.println("Done");
This prints Hot, then Done. At 25 it would print only Done, because the last line is outside the block.
The condition must be a boolean: if (temp = 30) does not compile, because temp = 30 is an assignment, not a comparison. Without braces, only the next single statement belongs to the if, so write braces every time. The if and else syntax is not on the Java Quick Reference: Learn this.
Check yourself
Show answerHide answer
It prints only Done. 30 > 30 is false, so the block is skipped.
How does if-else choose between two paths?
Adding else gives two-way selection. When the condition is true the if block runs; otherwise the else block runs. Exactly one of the two runs, never both and never neither.
int score = 64;
if (score >= 65)
{
System.out.println("Pass");
}
else
{
System.out.println("Retake");
}
64 >= 65 is false, so this prints Retake. The else has no condition of its own: it catches every case the if rejects.
Always trace the boundary, the value where the condition switches. With >=, a score of exactly 65 passes; with >, it would not, so the boundary is where a wrong operator shows up.
Check yourself
Show answerHide answer
It prints Pass, because 65 >= 65 is true.
Why does the order in an else-if chain matter?
An else-if chain gives multiway selection. Java tests the conditions from the top; the first true one runs its block, and the rest of the chain is skipped, even if later conditions are also true. A final else runs only when every condition was false; without one, no branch may run.
So when conditions overlap, their order decides the result. This chain should set level 2 for 80 points or more and level 1 for 50 to 79:
int pts = 90;
int level = 0;
if (pts >= 50)
{
level = 1;
}
else if (pts >= 80)
{
level = 2;
}
For 90 points, 90 >= 50 is true, so level becomes 1 and the second test is never reached. No value can reach level = 2, because anything at least 80 is also at least 50. Testing pts >= 80 first fixes it.
Key idea
When overlapping ranges are tested with >=, put the largest limit first; with <=, put the smallest limit first.
Check yourself
Show answerHide answer
level is 2: 80 >= 80 is true, so the first branch runs.
How does Java pair an else with nested ifs?
Without braces, Java pairs each else with the nearest earlier if in the same block that has no else yet. Indentation is ignored.
int a = 5;
if (a > 0)
if (a > 10)
System.out.println("big");
else
System.out.println("not positive");
The else is lined up with if (a > 0), but it belongs to if (a > 10). For 5, the outer test is true and the inner one false, so it prints not positive. For -2, nothing prints, because the whole inner if-else is skipped. Putting the inner if in its own block makes the else pair with the outer if.
Check yourself
Show answerHide answer
It prints big: both tests are true, so the inner if block runs and its else is skipped.
Worked example 1: Trace an else-if chain
Question: What is printed when this code segment runs?
int temp = 18;
String advice;
if (temp >= 25)
{
advice = "shorts";
}
else if (temp >= 15)
{
advice = "t-shirt";
}
else if (temp >= 5)
{
advice = "jacket";
}
else
{
advice = "coat";
}
System.out.println(advice + " at " + temp);
What tells you the method
One chain and one input, so test the conditions in order and stop at the first true one.
Step 1: Test each condition from the top.
Condition With temp= 18Result temp >= 2518 >= 25falsetemp >= 1518 >= 15true, so stopWhyOnly the first
truecondition runs its block; the rest is never reached.Step 2: Build the output.
adviceis "t-shirt", and+joins it with " at " and 18.WhyWith a
Stringoperand,+joins rather than adds.
Check it
At the boundary 15, 15 >= 15 is the first true test, giving t-shirt; at 25 the first test is true, giving shorts, as intended.
Answer
t-shirt at 18
Worked example 2: Design a method with three branches
Question: A cinema ticket costs 6 dollars under age 12, 7 dollars at 65 or over and 11 dollars otherwise. Design a method price(int age) that returns the price, then state what price(65) returns.
What tells you the method
A design task with three separate groups, so plan an else-if chain, then test it by tracing.
Step 1: State the input, the output and the plan.
Input: an
intage. Output: anintprice. Each age is in exactly one group, so use one chain with areturnper branch, and let the finalelsecatch the middle group.WhyA chain gives exactly one price for every age.
Step 2: Write the method.
public static int price(int age) { if (age < 12) { return 6; } else if (age >= 65) { return 7; } else { return 11; } }WhyAfter the two special groups, only ages 12 to 64 reach the
else.Step 3: Trace
price(65).65 < 12isfalse, then65 >= 65istrue, so the method returns 7.Why65 is the boundary of the oldest group, and
>=includes it.
Check it
At the other boundary, price(11) returns 6 and price(12) returns 11, because 12 < 12 and 12 >= 65 are both false.
Answer
7
Worked example 3: Nested ifs without braces
Question: What is printed when this code segment runs?
int m = 7;
int n = 3;
if (m > 5)
if (n > 5)
System.out.println("both big");
else
System.out.println("small m");
System.out.println("end");
- A)
end - B)
small mthenend - C)
both bigthenend - D)
small m
What tells you the method
Nested if statements with no braces, so decide which if owns the else, then trace.
Step 1: Pair the else.
The
elsepairs withif (n > 5), the nearestifwithout anelse.WhyJava ignores indentation.
Step 2: Trace.
m > 5istrue, so the innerif-elseruns;n > 5isfalse, so itselseprints small m. The last line belongs to neitherif, so end always prints.WhyWithout braces, an
iforelsecontrols only the next statement. A pairs theelsewith the outerif, C ignores thefalseinner test and D puts the lastprintlninside theelse.
Check it
With m equal to 2, the inner statement is skipped and only end prints; pairing the else with the outer if would wrongly add small m.
Answer
B
Your turn
Question: What is printed when this code segment runs?
int n = 30;
String label = "";
if (n % 3 == 0)
{
label = label + "Fizz";
}
else if (n % 5 == 0)
{
label = label + "Buzz";
}
if (n % 10 == 0)
{
label = label + "Ten";
}
System.out.println(label);
Step 1: Trace the else-if chain.
30 % 3is 0, so the first condition istrueandlabelbecomes "Fizz". Theelse ifis skipped, even though30 % 5 == 0is alsotrue.Step 2: Your go: decide whether the last
ifruns, then give the output.
Show the full solutionHide the solution
Step 2. The last if is a separate statement, not part of the chain, so it is always tested. 30 % 10 is 0, so its condition is true and "Ten" is added, making label "FizzTen".
Answer: FizzTen
Traps
Trap
A row of separate if statements works the same way as an else-if chain.
It seems right because the conditions look identical. But each separate if is tested, so several blocks can run, and an earlier block can change a later test. In a chain, at most one block runs.
With int x = 8, what is x after if (x > 5) { x = x + 10; } if (x > 15) { x = 0; } runs?
x is 0. The first block makes x 18, and the separate second if then tests 18 > 15, which is true.
Trap
The indentation shows which if an else belongs to.
It seems right because tidy code lines each else up with its if. But Java ignores indentation: without braces, an else pairs with the nearest earlier if that has no else.
In if (p) if (q) x = 1; else x = 2; which if does the else belong to?
It belongs to if (q), the nearest if without an else.
Trap
A semicolon straight after the condition, as in if (x > 0);, does no harm.
It seems right because Java statements end with semicolons. But that semicolon is an empty statement that becomes the whole body of the if, so the block after it runs every time.
What is printed by int x = -4; if (x > 0); { x = 0; } System.out.println(x);
0. The if controls only the empty statement, so { x = 0; } runs even though -4 > 0 is false.
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), multiple-choice questions ask what selection code prints or returns for a stated input, or which chain meets a description. In free response you write these statements in your own Java methods, for example in the methods and control structures question, where credit goes to conditions that handle every case, boundaries included.
Practice questions
- Recall An else-if chain has four branches, and the last one is a plain
else. Each time the chain runs, how many of its branches run?
Show answer
Answer: 1
Marking points:
- Java stops at the first condition that is
trueand skips the rest of the chain. - If no condition is
true, the finalelseruns, so exactly one branch runs every time.
- Apply What is printed when this code segment runs?
int stock = 0;
if (stock > 0)
{
System.out.println("In stock");
}
else
{
System.out.println("Sold out");
}
System.out.println(stock);
Show answer
Answer: Sold out then 0 on the next line.
Marking points:
0 > 0isfalse, so theelseblock prints Sold out.- The last
printlnis outside theif-else, so it always runs and prints 0.
- Apply What is printed when this code segment runs?
int k = 8;
if (k > 5)
{
k = k - 4;
}
if (k > 3)
{
k = k * 3;
}
else
{
k = k + 10;
}
System.out.println(k);
- A) 4
- B) 24
- C) 22
- D) 12
Show answer
Answer: D. The first if makes k 4. The second if is a separate statement, so it tests 4 > 3, which is true, and k becomes 12.
Why the others are wrong:
- A treats the two
ifstatements as one chain and stops after the first block. - B multiplies the original 8 by 3, ignoring the change made by the first block.
- C runs both the
ifblock and theelseblock, but only one of them runs.
- Apply What value does the call
zone(-3, 0)return?
public static int zone(int x, int y)
{
if (x >= 0)
{
if (y >= 0)
{
return 1;
}
return 4;
}
if (y >= 0)
{
return 2;
}
return 3;
}
Show answer
Answer: 2
Marking points:
-3 >= 0isfalse, so the whole outer block, includingreturn 4;, is skipped.0 >= 0istrue, so the method returns 2.
- Exam-style The
String medalshould be "gold" for 1000 points or more, "silver" for 500 to 999 and "bronze" below 500. Assumeint ptsis not negative. Which code segment works for everypts?
-
A)
if (pts >= 1000) { medal = "gold"; } else if (pts >= 500) { medal = "silver"; } else { medal = "bronze"; } -
B)
if (pts >= 500) { medal = "silver"; } else if (pts >= 1000) { medal = "gold"; } else { medal = "bronze"; } -
C)
if (pts >= 1000) { medal = "gold"; } if (pts >= 500) { medal = "silver"; } else { medal = "bronze"; } -
D)
if (pts > 1000) { medal = "gold"; } else if (pts > 500) { medal = "silver"; } else { medal = "bronze"; }
Show answer
Answer: A. It tests the largest limit first, and >= includes both boundaries, so 1000 gives gold, 500 gives silver and 499 gives bronze.
Why the others are wrong:
- B has the conditions in the wrong order: any value of 1000 or more already passes
pts >= 500, so gold is never set. - C uses two separate
ifstatements, so for 1000 or more the secondifoverwrites gold with silver. - D uses
>instead of>=, so exactly 1000 gives silver and exactly 500 gives bronze.
- Exam-style The method should return how far apart
aandbare:distance(9, 4)anddistance(4, 9)should both return 5. Give the number of the line that stops it working.
1: public static int distance(int a, int b)
2: {
3: int d = a - b;
4: if (d < 0);
5: {
6: d = -d;
7: }
8: return d;
9: }
Show answer
Answer: Line 4.
Marking points:
- The semicolon on line 4 gives the
ifan empty body, so the block on lines 5 to 7 always runs. distance(9, 4)makesd5, then flips it to -5. Deleting the semicolon makes both calls return 5.
- Recall What is the name for a group of statements enclosed in a pair of braces?
Show answer
Answer: Block
Marking points:
- Java treats a block as one statement, which is how an
iforelsecan control several statements.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- An
ifruns its block only when the condition istrue; the statement after the block runs either way. - In an
if-else, exactly one of the two blocks runs. - An else-if chain stops at the first
truecondition, so overlapping tests go from the most restrictive to the least. - Without braces, an
iforelsecontrols one statement, and anelsepairs with the nearest unpairedif. - Separate
ifstatements are each tested, so more than one can run.