The if and else Statement in Java

Unit 2: Variables, Decisions, and Input · Lesson 2.4 · about 30 minutes · no coding experience needed

This is the moment a program stops being a list of instructions and starts making choices. Everything that makes a game feel alive comes from here.

What you will be able to do

  • Write an if statement with a condition and a body
  • Add an else branch and predict which one runs
  • Spot the stray semicolon that silently breaks an if

Words you will need

if statement
In plain words Do this, but only when that is true.
More precisely A control structure that executes its body when its condition is true.
Branch
In plain words One of the paths the program can take.
More precisely A block of statements reached only under a particular condition.
Block
In plain words The code between a pair of braces.
More precisely A brace-delimited group of statements treated as one unit.

Build it step by step

Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.

  1. Step 1

    A simple if statement in an editor with the condition and body labeled.
    if (score > 100)
    {
        Greenfoot.playSound("win.wav");
    }

    Read it as one sentence: IF score is greater than 100, play the sound.

    The condition goes in parentheses. The body goes in curly braces. If the condition is false, the whole body is skipped and the program carries straight on.

  2. Step 2

    An if statement with an else branch, both bodies visible.
    if (lives > 0)
    {
        move(4);
    }
    else
    {
        Greenfoot.stop();
    }

    else is the other path. EXACTLY ONE of the two bodies runs, always. Never both, never neither.

    Notice else has no condition of its own. It means "in every other case", so it does not need one.

  3. Step 3

    An if statement inside an act method controlling actor movement.
    public void act()
    {
        if (isAtEdge())
        {
            turn(180);
        }
        move(3);
    }

    Now it is doing real work. Every frame: check the edge, turn if needed, then move.

    Look at where `move(3)` sits. It is OUTSIDE the braces, so it runs every frame no matter what the condition said. Moving it inside the braces would mean the actor only moves when it is at the edge, which is a completely different game and a very common accident.

  4. Step 4

    An if statement with a stray semicolon after the condition, with the semicolon circled.
    if (score > 100);   // <-- this semicolon ends the if
    {
        Greenfoot.playSound("win.wav");
    }

    This compiles. It runs. It is wrong, and it will not tell you.

    The semicolon ends the if statement immediately, so the if now controls nothing at all. The braces below become an ordinary block that always runs, and your sound plays every single frame regardless of the score.

    There is no error message for this, ever. If an if seems to always run, look for this semicolon first.

Mistakes almost everyone makes here

These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.

Common wrong idea else runs after the if body.

What is actually true Exactly one branch runs. else is the alternative, not the continuation.

Why it matters Expecting both to run makes every branching program behave inexplicably.

Common wrong idea A semicolon after `if (...)` is harmless punctuation.

What is actually true It ends the if, so the block below always runs.

Why it matters It produces no error and no warning. It is the hardest bug in this unit to see.

Common wrong idea Code after the closing brace only runs when the condition was true.

What is actually true It runs either way. Only what is INSIDE the braces is conditional.

Why it matters This is the difference between an actor that patrols and one that never moves.

Common wrong idea Braces are optional so it is fine to leave them off.

What is actually true Java permits it, but adding a second line later silently breaks it.

Why it matters Only the first line is controlled by a brace-less if. The second always runs.

Check your understanding

Answer these before moving on. They are graded instantly and you can retry.

  1. 1. score is 50. What happens? if (score > 100) { move(4); } turn(10);

  2. 2. How many branches of an if/else run?

  3. 3. An if seems to run every single time even when the condition should be false. What would you check first?

  4. 4. Does else need a condition of its own?

Fill in the code

The player should lose a life when it touches a spike, and otherwise keep moving. Fill in the missing pieces.

 (isTouching(Spike.class))
{
    lives = lives - 1;
}

{
    move(3);
}
Stuck? Open a hint for each blank
  • Blank 1: The keyword that starts a decision.
  • Blank 2: The keyword for the other path. It takes no condition.

Lesson quiz

This one counts toward your progress. Take it when the section above makes sense.

  1. 1. What is wrong with `if (lives > 0);`?

  2. 2. lives is 0. Which runs? if (lives > 0) { move(4); } else { Greenfoot.stop(); }

  3. 3. Where does the condition of an if statement go?

  4. 4. Why does this course always use braces even for a one-line if?

The short version

  • Condition in parentheses, body in curly braces.
  • Exactly one branch of an if/else runs.
  • Code after the closing brace runs either way.
  • A semicolon after the condition silently breaks the if. No error, ever.

If you get stuck

These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.

Get in Touch

Whether you're a student, parent, or teacher, I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box. No message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours
✓

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for, whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]