JAVA • CONTROL FLOW

If/Else & Else-If Chains — Write if/else and else-if chains

Teach your programs to make decisions by choosing different paths based on conditions.

Historical Context & Motivation

Every useful program needs the ability to make decisions. Without decision-making, a program would simply execute every instruction from top to bottom in the same way every single time, regardless of user input or changing data. The concept of conditional branching — choosing which instructions to run based on whether a condition is true or false — is one of the oldest and most fundamental ideas in computing. From the earliest mechanical machines to modern Java applications, this idea has shaped how every program operates.

1843
Ada Lovelace's Notes
Ada Lovelace described how Charles Babbage's Analytical Engine could branch to different instruction sequences based on conditions, making her the first person to articulate conditional logic in computing.
1957
FORTRAN's IF Statement
FORTRAN, one of the first high-level programming languages, introduced the arithmetic IF statement, allowing programs to jump to different lines of code depending on whether a value was negative, zero, or positive.
1972
C Language Structured If/Else
Dennis Ritchie's C language introduced the structured if/else syntax with curly braces that Java would later adopt. This clean block-based approach replaced messy GOTO jumps and became the industry standard.
1995
Java Adopts If/Else
James Gosling and his team at Sun Microsystems released Java, which inherited the if/else and else-if syntax from C. Java's clear, readable style made these constructs accessible to millions of new programmers.

Imagine you are building a grading program. You need the computer to print "A" when a score is 90 or above, "B" when it's between 80 and 89, and so on. Without conditional branching, this would be impossible. The central question this lesson answers is: how do we tell a Java program to choose between multiple paths of execution?

Core Principles & Definitions

Before writing any if/else code, you need to understand the building blocks that make conditional logic work. Java evaluates a boolean expression — a statement that resolves to either true or false — and then uses that result to decide which block of code to execute. Here are the foundational concepts you need to know.

1

Boolean Expression

A condition that evaluates to true or false. Examples include score >= 90 and age < 18. These are the gatekeepers of your if statements.
2

If Block

The code enclosed in curly braces after the if keyword. This block executes only when the boolean expression is true. If the condition is false, this block is skipped entirely.
3

Else Block

The fallback code that executes when the if condition is false. It guarantees that one of the two blocks always runs, providing a default behavior.
4

Else-If Chain

A sequence of conditions tested one after another. Java checks each condition from top to bottom and executes the first block whose condition is true, then skips all remaining blocks in the chain.
5

Mutual Exclusivity

In an if/else-if/else chain, exactly one block executes. Once Java finds a true condition, it runs that block and jumps past the rest. This means the order of your conditions matters greatly.
✦ KEY TAKEAWAY
Think of an if/else-if chain like a series of doors in a hallway. You walk up to the first door and check if it's unlocked (the condition is true). If it is, you walk through and you're done — you don't check any more doors. If it's locked, you move to the next door. The else block at the end is the emergency exit: it's always open if every other door was locked.

Visual Explanation — How If/Else-If Flows

The best way to understand if/else-if chains is to visualize the flow of execution. In the diagram below, you can see how the Java runtime evaluates each condition in order and takes the first path where the condition is true. Notice that once a branch is taken, all remaining conditions are skipped.

This flowchart shows a simplified grading example. The program checks score >= 90 first. If true, it prints "A" and skips everything else. If false, it moves to score >= 80. If that is also false, the else block catches everything remaining.

Notice how each diamond shape represents a decision point where the program evaluates a boolean expression. The green "true" arrows lead directly to a code block, while the red "false" arrows move on to the next condition. Every path eventually converges at the bottom, meaning the program always continues executing after the entire chain regardless of which branch was taken.

How If/Else-If Chains Work in Java

Now let's look at the exact Java syntax. Every if/else-if chain follows a predictable pattern: you begin with if, then add as many else if branches as you need, and optionally finish with a single else block to handle any remaining cases.

Pattern 1 — Simple If

SIMPLE IF SYNTAX
if (condition) { // runs only when condition is true }
The condition must be a boolean expression (evaluates to true or false). The code block inside the curly braces runs only when the condition is true; otherwise, it is skipped and execution continues below.

Pattern 2 — If/Else

IF/ELSE SYNTAX
if (condition) { // runs when condition is true } else { // runs when condition is false }
Exactly one of the two blocks will always execute. If the condition is true, the first block runs. If false, the else block runs. There is no scenario where neither block executes.

Pattern 3 — If/Else-If/Else Chain

ELSE-IF CHAIN SYNTAX
if (condition1) { // block A } else if (condition2) { // block B } else if (condition3) { // block C } else { // default block D }
Java checks condition1 first. If true, block A runs and the rest is skipped. If condition1 is false, it checks condition2, then condition3, and so on. The final else is optional but recommended as a safety net to catch unexpected values.
⚠️ Common Mistake Alert
Always use == (double equals) for comparison in conditions, not = (single equals). The single equals sign is the assignment operator. Writing if (x = 5) instead of if (x == 5) is a logic error. Fortunately, Java usually catches this as a compile-time error since the assignment doesn't produce a boolean.

Detailed Syntax Breakdown & Code Structure

Let's examine a complete, real Java program that uses an if/else-if chain to assign letter grades. Pay close attention to how the conditions are ordered from highest to lowest — this is a critical design decision that affects correctness.

This annotated code shows the complete grading program. With score = 85, the first condition (≥ 90) is false, so the second condition (≥ 80) is checked. Since 85 ≥ 80 is true, "Grade: B" is printed and all remaining conditions are skipped.

A crucial point: the conditions are ordered from most restrictive to least restrictive (90, then 80, then 70, then 60). If you reversed this order and checked score >= 60 first, then a student with a score of 95 would get a "D" because 95 ≥ 60 is true and the program would stop there. Order matters!

Worked Example — Temperature Advisor

Let's build a program from scratch that reads a temperature value and prints a clothing recommendation. We'll walk through every decision step by step.

Temperature-Based Clothing Advisor
1
Step 1 — Identify the Variable and RangesWe have an integer variable int tempF = 45; representing the temperature in Fahrenheit. We want four categories: below 32 (freezing — wear a heavy coat), 32–59 (cold — wear a jacket), 60–79 (mild — wear a light layer), and 80+ (hot — wear shorts and a t-shirt).
2
Step 2 — Write the If/Else-If ChainWe order conditions from the most extreme to the least extreme. The code looks like this: if (tempF < 32) prints "Wear a heavy coat — it's freezing!". Then else if (tempF < 60) prints "Wear a jacket — it's cold.". Then else if (tempF < 80) prints "A light layer should be fine.". Finally, else prints "Shorts and a t-shirt — it's hot!"
3
Step 3 — Trace the Execution for tempF = 45Java evaluates tempF < 32 → 45 < 32 is false, so skip. Next, tempF < 60 → 45 < 60 is true, so this block runs and we skip everything else.
Output: "Wear a jacket — it's cold."
4
Step 4 — Verify the Condition Order LogicNotice that we don't need to write tempF >= 32 && tempF < 60 for the second condition. Because it's an else-if, we already know the first condition was false, meaning tempF is NOT less than 32. Therefore, tempF must be ≥ 32, and we only need to check tempF < 60. This simplification is a key advantage of chained else-if over separate if statements.
The else-if chain implicitly narrows the range with each step, so you never need to re-check earlier conditions.

If/Else-If vs. Separate If Statements

A common question for beginners is: "Why not just use multiple separate if statements instead of an else-if chain?" The answer has to do with both correctness and efficiency. Let's compare the two approaches side by side.

Comparison of if/else-if chains versus separate if statements
FeatureIf/Else-If ChainSeparate If Statements
How many blocks can run?Exactly one block runsMultiple blocks can run
EfficiencyStops checking after first true conditionChecks every condition regardless
Mutual exclusivityGuaranteed — only one path is takenNot guaranteed — must use non-overlapping conditions manually
Range narrowingImplicit — previous false conditions narrow the rangeMust explicitly state full range in each condition
Best used whenCategories are mutually exclusive (grades, temperature ranges)Conditions are independent (check multiple flags separately)
✦ KEY TAKEAWAY
Use an if/else-if chain when your conditions are like a multiple-choice question where only one answer is correct. Use separate if statements when your conditions are like a checklist where multiple items might apply simultaneously. For example, a grading system needs else-if (a student gets exactly one grade), but a notification system might need separate if statements (a user could have new emails AND new messages AND a system alert, all at the same time).

Connection to Advanced Control Flow

Once you're comfortable with if/else-if chains, you'll encounter more advanced ways to handle decision-making in Java. The table below shows how if/else-if connects to concepts you'll learn later.

How if/else-if chains connect to more advanced Java concepts
ConceptIf/Else-If (What You Know)Advanced Version
Switch StatementsChain of else-if blocks testing one variable against different valuesA cleaner syntax for comparing one variable against many constant values using switch/case
Ternary OperatorSimple if/else that assigns one of two values to a variableShorthand: result = (condition) ? valueA : valueB;
Nested If StatementsSequential checking of one condition at a timePlacing an if/else inside another if/else for multi-dimensional decisions (use cautiously to avoid deep nesting)
Logical OperatorsOne boolean expression per conditionCombine multiple conditions with && (and), || (or), and ! (not) for complex decisions

As you progress, you'll find that if/else-if chains remain one of the most commonly used control flow structures, even in professional-level code. Mastering them now gives you a strong foundation for every other branching mechanism you'll encounter. In particular, understanding condition ordering and mutual exclusivity will carry over directly into switch statements, pattern matching, and even how you design methods and classes in object-oriented programming.

Practice Problems

PROBLEM 1 — CONCEPTUAL
In an if/else-if/else chain, is it possible for more than one block to execute? Explain why or why not.
PROBLEM 2 — BASIC CALCULATION
What does the following code print? Trace the execution step by step. int x = 15; if (x > 20) { System.out.println("Big"); } else if (x > 10) { System.out.println("Medium"); } else { System.out.println("Small"); }
PROBLEM 3 — INTERMEDIATE
A programmer writes the following grading code but gets incorrect results. Identify the bug and explain how to fix it. int score = 95; if (score >= 60) { System.out.println("D"); } else if (score >= 70) { System.out.println("C"); } else if (score >= 80) { System.out.println("B"); } else if (score >= 90) { System.out.println("A"); }
PROBLEM 4 — APPLIED
Write a complete if/else-if/else chain for a movie ticket pricing system. The rules are: children (age < 13) pay $8, teens (age 13–17) pay $11, adults (age 18–64) pay $14, and seniors (age 65+) pay $9. Assume the variable int age is already declared. Write the code and explain your condition ordering.
PROBLEM 5 — CRITICAL THINKING
Consider two different approaches: (A) a single if/else-if/else chain with 4 conditions, and (B) four separate if statements each with a fully specified range (e.g., if (score >= 90 && score <= 100)). Both produce the same output for valid inputs. Under what circumstances could approach (B) produce unexpected behavior that approach (A) would not? Discuss at least two scenarios.

Lesson Summary

In this lesson you learned how Java uses if/else and else-if chains to make decisions based on boolean expressions. A simple if statement executes a block only when its condition is true. Adding an else block guarantees a default path when the condition is false. Chaining multiple else-if conditions lets you handle many categories while ensuring mutual exclusivity — exactly one block runs per chain.

The most important design rule is condition ordering: place the most restrictive condition first so that broader conditions don't accidentally match before narrower ones. Remember that else-if chains implicitly narrow the value range at each step, which simplifies your conditions and reduces bugs. These fundamentals prepare you for more advanced constructs like switch statements, the ternary operator, and nested conditionals.

Varsity Tutors • Java • If/Else & Else-If Chains — Write if/else and else-if chains