Skip to content

Lesson 01 · Conditionals — if / else

Objectives

After this lesson you will be able to:

  • Write if/else if/else chains and reason about block scope.
  • Avoid the dangling-else and missing-braces traps the exam exploits.
  • Remember that an if condition must be a boolean — Java has no truthiness.

if, else if, else

An if runs its body only when a boolean condition is true. Java has no truthiness, so the condition cannot be an int or a reference.

java
int score = 72;
if (score >= 90) {
    grade = 'A';
} else if (score >= 60) {
    grade = 'C';
} else {
    grade = 'F';
}

Exam trap

The condition must be boolean. if (x = 5) only compiles if x is a boolean (it's an assignment, not a comparison); if (5) and if (someObject) never compile.

Braces, scope, and the single-statement body

If you omit braces, the if governs exactly one statement. Indentation is irrelevant to the compiler — only the syntax matters.

java
if (ready)
    log("go");
    fire();        // NOT part of the if — always runs

A variable declared inside a block is scoped to that block:

java
if (cond) {
    int local = 1;
}
// local is out of scope here — using it does not compile

SDET note

Always use braces, even for one-liners. It removes the "second statement runs unconditionally" bug class entirely and keeps diffs clean when a branch later grows a second line.

The dangling else

An else binds to the nearest unmatched if, regardless of indentation. This is the classic dangling-else trap:

java
if (a)
    if (b)
        x();
    else            // binds to `if (b)`, NOT `if (a)`
        y();

If you intend the else to belong to the outer if, add braces:

java
if (a) {
    if (b) x();
} else {
    y();            // now belongs to `if (a)`
}

Key Takeaways

  • An if condition must be a boolean; there is no truthiness in Java.
  • Without braces an if/else controls exactly one statement — later lines run unconditionally.
  • A bare else binds to the nearest if; brace the outer if to redirect it.
  • Variables are block-scoped — they don't escape the { } they're declared in.

Lesson Quiz

Lesson Quiz · Conditionals0 / 4
  1. What does this print?

    boolean ready = false;
    if (ready)
        System.out.print("a");
        System.out.print("b");
    • Aa
    • Bb
    • Cab
    • Dnothing
  2. Which condition does NOT compile?

    • Aif (x > 0)
    • Bif (flag)
    • Cif (count)
    • Dif (a == b)
  3. Given a=true, b=false, what runs?

    if (a)
        if (b)
            x();
        else
            y();
    • Ax()
    • By()
    • Cneither
    • Dboth
  4. Is this legal?

    if (cond) {
        int n = 1;
    }
    System.out.println(n);
    • APrints 1
    • BPrints 0
    • CCompile error: n out of scope
    • DRuntime error

Next: The switch. Run the matching code in labs/src/main/java/com/jse21/m02_flow/Conditionals.java.