Program Flow  «Prev  Next»
Lesson 2Conditional Branching Basics
ObjectiveLearn how to control program flow based on a condition in Java

Conditional Branching Basics in Java

Branches in Java allow a program to alter the flow of execution by making decisions based on conditions. This means the program can choose between different paths of execution, instead of always running code linearly from top to bottom. Here's how it works:
🔹 What Is "Flow of Execution"?
The flow of execution is the order in which statements, instructions, and function calls are executed in a program. By default, Java runs code from top to bottom. But branching introduces conditions that change that order.
🔹 How Branching Alters the Flow
Branching uses conditional statements to test whether a condition is `true` or `false`. Based on that result, Java will:
  • Execute one block of code
  • Skip other blocks

🔹 Main Branching Constructs in Java
  1. if Statement
    int age = 20;
    
    if (age >= 18) {
      System.out.println("You can vote.");
    }
        

    ✅ If the condition is true, the code inside runs. Otherwise, it's skipped.
  2. if-else Statement
    if (age >= 18) {
      System.out.println("You can vote.");
    } else {
      System.out.println("You are too young to vote.");
    }
        

    Only one of the two blocks will execute, based on the condition.
  3. if-else if-else Chain
    int score = 85;
    
    if (score >= 90) {
      System.out.println("Grade A");
    } else if (score >= 80) {
      System.out.println("Grade B");
    } else {
      System.out.println("Grade C or below");
    }
        

    This allows multiple possible paths, but only one will run.
  4. switch Statement is used for exact matches on a single variable:
    int day = 2;
    
    switch (day) {
      case 1: System.out.println("Monday"); break;
      case 2: System.out.println("Tuesday"); break;
      default: System.out.println("Other day");
    }
        

    Java will jump to the case that matches and execute from there (unless you use break).

✅ Summary
Branches allow your Java program to:
  • Make decisions during runtime
  • Skip certain lines of code
  • Execute only what's necessary
  • Handle complex logic like menus, game states, user input, etc.

Without branches, a program would always execute the same steps. Hence, branches allow your program to execute different paths.

Branches allow a Java program to alter the flow of execution and run one piece of code instead of another. The figure below shows how a Java program flows without branches:
Java program without branches
Java program without branches

A Java program without branches executes one statement at a time from start to end. Although technically there is nothing wrong with the program in the figure, it is extremely limited in terms of what it can do. More specifically, there is no way for it to take a different path of execution. The following figure shows how a branch gives the program more freedom:
Java program with branches
  1. Start
    • The process begins.
  2. Execute Statement 1
    • Perform the first operation.
  3. Evaluate Conditional Branch
    • A decision is made based on a condition:
      • If the condition is true, proceed to Statement 4.
      • If the condition is false, proceed to Statement 2.
  4. Execute Statement 2 (only if condition is false)
    • Perform the second operation.
  5. Execute Statement 3
    • This follows either Statement 2 or Statement 4.
  6. End
    • The process ends.


Based on the flowchart above, here is the corresponding Java code that represents its logic:
public class FlowchartExample {

    public static void main(String[] args) {
        // Start
        statement1();

        // Conditional Branch
        if (condition()) {
            // If condition is true
            statement4();
        } else {
            // If condition is false
            statement2();
        }

        // Common path
        statement3();

        // End
    }

    public static void statement1() {
        System.out.println("Executing Statement 1");
    }

    public static boolean condition() {
        // Replace this with actual condition logic
        return true; // or false depending on your scenario
    }

    public static void statement2() {
        System.out.println("Executing Statement 2");
    }

    public static void statement3() {
        System.out.println("Executing Statement 3");
    }

    public static void statement4() {
        System.out.println("Executing Statement 4");
    }
}

Notes:
  • The condition() method simulates the conditional branch in the flowchart.
  • You can modify the condition() method to implement real logic.
  • Each statementX() method represents a block in the flowchart.

The if-else statement

The if-else statement allows you to conditionally execute one section of code or another. Because of its simplicity and wide range of usefulness, the if-else statement is the most commonly used branch in Java.
The syntax for the if-else statement follows:
if (Condition)
  Statement1
else
  Statement2

If the Boolean Condition is true, Statement1 is executed; otherwise Statement2 is executed.
Following is a simple example:
if (tired)
 timeForBed = true;
else
 timeForBed = false;


If the Boolean variable tired is true, the first statement is executed and timeForBed is set to true.
Otherwise the second statement is executed and timeForBed is set to false.
The else part of the if-else statement is optional. In other words, you can leave it off if you have only a single statement that you want to execute conditionally.
It is also possible to link together a series of if-else statements to get the effect of multiple branches.
Variables: Variables are locations in memory that are used to store information. You can think of variables as storage containers designed to hold data of a certain type.
You are not limited to executing an individual line of code with the if-else statement. To execute multiple lines of code you can use a compound statement, which is a block of code surrounded by curly braces ({}). An if-else statement interprets a compound statement as a single statement. Following is an example that demonstrates using a compound statement:
if (printVitals) {
  System.out.println("Pulse rate: " + pulse);
  System.out.println("Blood pressure: " + pressure);
  System.out.println("Temperature: " + temp);
}

SEMrush Software