AP · Computer Science A · Boolean Expressions and if Statements

if, if-else and else-if Statements

14 min readUpdated December 1, 2026FreeAP Computer Science A, Selection and Iteration

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

  1. 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.

  2. If int n = 9, is n % 2 == 0 true or false?Show answerHide answer

    It is false: 9 % 2 is 1, not 0, so 9 is odd.

  3. An if-else statement has two blocks. How many of them run each time the statement runs?Show answerHide answer

    Exactly one: the if block when the condition is true, the else block when it is false.

Know these already? Jump to the practice questions

What you'll be able to do

  • Identify which branch of an if, if-else or 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 if statements, including an else written without braces.
  • Choose between separate if statements 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

With int temp = 30, what does the code segment in this section print?
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

What does the code print when score is 65?
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

After the two tests are swapped, what is level when pts is 80?
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

What does the code in this section print when a is 12?
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.

  1. Step 1: Test each condition from the top.

    ConditionWith temp = 18Result
    temp >= 2518 >= 25false
    temp >= 1518 >= 15true, so stop
    Why

    Only the first true condition runs its block; the rest is never reached.

  2. Step 2: Build the output.

    advice is "t-shirt", and + joins it with " at " and 18.

    Why

    With a String operand, + 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.

  1. Step 1: State the input, the output and the plan.

    Input: an int age. Output: an int price. Each age is in exactly one group, so use one chain with a return per branch, and let the final else catch the middle group.

    Why

    A chain gives exactly one price for every age.

  2. 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;
        }
    }
    
    Why

    After the two special groups, only ages 12 to 64 reach the else.

  3. Step 3: Trace price(65).

    65 < 12 is false, then 65 >= 65 is true, so the method returns 7.

    Why

    65 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 m then end
  • C) both big then end
  • D) small m

What tells you the method

Nested if statements with no braces, so decide which if owns the else, then trace.

  1. Step 1: Pair the else.

    The else pairs with if (n > 5), the nearest if without an else.

    Why

    Java ignores indentation.

  2. Step 2: Trace.

    m > 5 is true, so the inner if-else runs; n > 5 is false, so its else prints small m. The last line belongs to neither if, so end always prints.

    Why

    Without braces, an if or else controls only the next statement. A pairs the else with the outer if, C ignores the false inner test and D puts the last println inside the else.

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);
  1. Step 1: Trace the else-if chain.

    30 % 3 is 0, so the first condition is true and label becomes "Fizz". The else if is skipped, even though 30 % 5 == 0 is also true.

  2. Step 2: Your go: decide whether the last if runs, 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

  1. 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 true and skips the rest of the chain.
  • If no condition is true, the final else runs, so exactly one branch runs every time.
  1. 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 > 0 is false, so the else block prints Sold out.
  • The last println is outside the if-else, so it always runs and prints 0.
  1. 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 if statements 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 if block and the else block, but only one of them runs.
  1. 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 >= 0 is false, so the whole outer block, including return 4;, is skipped.
  • 0 >= 0 is true, so the method returns 2.
  1. Exam-style The String medal should be "gold" for 1000 points or more, "silver" for 500 to 999 and "bronze" below 500. Assume int pts is not negative. Which code segment works for every pts?
  • 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 if statements, so for 1000 or more the second if overwrites gold with silver.
  • D uses > instead of >=, so exactly 1000 gives silver and exactly 500 gives bronze.
  1. Exam-style The method should return how far apart a and b are: distance(9, 4) and distance(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 if an empty body, so the block on lines 5 to 7 always runs.
  • distance(9, 4) makes d 5, then flips it to -5. Deleting the semicolon makes both calls return 5.
  1. 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 if or else can control several statements.

Key points

Recall, then reveal

Say the main points from memory first, then check them.

Show key pointsHide key points
  • An if runs its block only when the condition is true; 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 true condition, so overlapping tests go from the most restrictive to the least.
  • Without braces, an if or else controls one statement, and an else pairs with the nearest unpaired if.
  • Separate if statements are each tested, so more than one can run.

Keep learning

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Selection and Iteration

All Boolean Expressions and if Statements notes

Part of Novark's AP Computer Science A notes