Skip to content

VOL 01 / CH 04 / LESSON 01

4.1 if, else and Conditional Boundaries ​

Prerequisites: Boolean expressions and short-circuit logic Estimated time: 25 minutes You are ready to continue when: You can write mutually exclusive branches, handle boundary values, and avoid dangling else

if Accepts Only Boolean Conditions ​

java
boolean authenticated = true;
int accessLevel = 6;

if (authenticated && accessLevel >= 5) {
    System.out.println("access granted");
} else {
    System.out.println("access denied");
}

An if condition must be boolean or a Boolean that can be unboxed. Integers cannot stand in for true or false; unboxing a null Boolean throws NullPointerException:

java
int count = 1;
// if (count) { } // Compilation error

Conditions are evaluated first, and only one of the two branches is executed. If the condition evaluation itself throws an exception, neither branch begins.

else if Selecting the First Matching Item from Top to Bottom ​

java
int score = 82;
String grade;

if (score < 0 || score > 100) {
    grade = "invalid";
} else if (score >= 90) {
    grade = "excellent";
} else if (score >= 80) {
    grade = "good";
} else if (score >= 60) {
    grade = "pass";
} else {
    grade = "retry";
}

Once a condition is true, subsequent branches are not evaluated. The order is part of the business logic: if you write score >= 60 first, 82 will prematurely enter pass.

Boundaries should be tested in groups: -1, 0, 59, 60, 79, 80, 89, 90, 100, 101. Testing only 82 cannot prove the correctness of the range.

Independent if Statements and Mutually Exclusive Branches ​

java
if (temperature < 0) {
    System.out.println("freezing");
}
if (temperature < 10) {
    System.out.println("cold");
}

Both will execute when the temperature is -5. If the business only allows one tag, use a mutually exclusive if / else if / else chain, or define the interval clearly first.

Always Use Braces ​

Java allows omitting braces for a single statement:

java
if (ready)
    start();

But it's easy to create visual misdirection when adding a second line:

java
if (ready)
    start();
    recordMetric(); // Runs regardless of ready

Tutorials and team code consistently use braces:

java
if (ready) {
    start();
    recordMetric();
}

This is a style constraint to reduce maintenance risks, not because the Java syntax of omitting braces is invalid.

else Binds to the Nearest Unpaired if ​

java
if (member)
    if (spent >= 100)
        discount();
    else
        explainThreshold();

The else here belongs to the inner if (spent >= 100). Indentation does not change the binding. Adding braces clarifies the intent:

java
if (member) {
    if (spent >= 100) {
        discount();
    } else {
        explainThreshold();
    }
}

Using Early Returns to Reduce Nesting ​

Consecutive invalid conditions in a method can exit early:

java
static String route(boolean authenticated, int accessLevel) {
    if (!authenticated) {
        return "sign-in";
    }
    if (accessLevel < 5) {
        return "request-access";
    }
    return "dashboard";
}

Early returns are not a fixed rule. If a method requires uniform cleanup or transaction boundaries, combine them with try, resource management, and team agreements.

java
boolean expected = false;
boolean actual = true;

if (expected = actual) {
    System.out.println("runs");
}

It compiles because the assignment expression has type boolean. Here, the assigned value is true, so the branch also runs. Avoid assigning within conditions and enable IDE checks or static analysis.

Professional Quick Reference ​

RequirementApproach
Two-way choiceif / else
Multiple mutually exclusive rangesWrite in boundary order else if
Multiple conditions that may all executeMultiple independent if
Null-safe conditionsCheck for null first, then use &&
Reduce nestingSmall methods, early returns, named boolean expressions
Prove boundary correctnessTest each boundary point on both sides and invalid inputs

Before Moving On ​

Do a verbal check using the score range: why must 82 pass through score >= 90 before reaching score >= 80, and why might the two separate ifs be able to execute simultaneously? List adjacent values for the three boundaries of 60, 80, and 90. Also identify which if owns each else, and whether each condition compares a value or assigns one.

→ Next: switch Statements and Expressions

Specification: JLS §14.9: if Statement.

Built with VitePress | Software Systems Atlas