Virtual assistance

Control Flow Statements

Control flow statements allow you to control the order of execution of statements in a program. Learn about decision-making and branching in Java.

Java Control Flow Statements Tutorial

What are Control Flow Statements?

Control flow statements in Java allow you to control the flow of execution in your program. They enable decision-making, looping, and branching based on conditions. The main types of control flow statements are:

  • Decision-making statements: if, if-else, nested if, switch
  • Looping statements: for, while, do-while (covered in the next tutorial)
  • Branching statements: break, continue, return

The if Statement

The if statement is the most basic decision-making statement. It executes a block of code only if a specified condition is true.

Syntax

if (condition) {
    // code to be executed if condition is true
}

if Statement Example

public class IfStatement {
    public static void main(String[] args) {
        int age = 18;

        if (age >= 18) {
            System.out.println("You are eligible to vote.");
        }

        System.out.println("This statement always executes.");
    }
}

The if-else Statement

The if-else statement provides an alternative path of execution when the condition is false.

Syntax

if (condition) {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

if-else Statement Example

public class IfElseStatement {
    public static void main(String[] args) {
        int number = 10;

        if (number % 2 == 0) {
            System.out.println(number + " is even.");
        } else {
            System.out.println(number + " is odd.");
        }

        // Another example
        int marks = 85;
        if (marks >= 60) {
            System.out.println("You passed the exam!");
        } else {
            System.out.println("You failed the exam.");
        }
    }
}

The if-else-if Ladder

The if-else-if ladder allows you to test multiple conditions sequentially.

Syntax

if (condition1) {
    // code to be executed if condition1 is true
} else if (condition2) {
    // code to be executed if condition2 is true
} else if (condition3) {
    // code to be executed if condition3 is true
} else {
    // code to be executed if all conditions are false
}

if-else-if Ladder Example

public class IfElseIfLadder {
    public static void main(String[] args) {
        int marks = 75;

        if (marks >= 90) {
            System.out.println("Grade: A+");
        } else if (marks >= 80) {
            System.out.println("Grade: A");
        } else if (marks >= 70) {
            System.out.println("Grade: B");
        } else if (marks >= 60) {
            System.out.println("Grade: C");
        } else if (marks >= 50) {
            System.out.println("Grade: D");
        } else {
            System.out.println("Grade: F");
        }

        // Another example: Temperature classification
        double temperature = 25.5;

        if (temperature >= 40) {
            System.out.println("Very Hot");
        } else if (temperature >= 30) {
            System.out.println("Hot");
        } else if (temperature >= 20) {
            System.out.println("Warm");
        } else if (temperature >= 10) {
            System.out.println("Cool");
        } else {
            System.out.println("Cold");
        }
    }
}

Nested if Statements

Nested if statements are if statements inside other if statements. They allow for more complex decision-making.

Syntax

if (condition1) {
    // outer if block
    if (condition2) {
        // inner if block
        // code to be executed if both condition1 and condition2 are true
    }
}

Nested if Example

public class NestedIf {
    public static void main(String[] args) {
        int age = 25;
        boolean hasLicense = true;

        if (age >= 18) {
            System.out.println("You are eligible for a driving license.");
            if (hasLicense) {
                System.out.println("You already have a driving license.");
            } else {
                System.out.println("You can apply for a driving license.");
            }
        } else {
            System.out.println("You are not eligible for a driving license yet.");
        }

        // Another example: Admission criteria
        int mathMarks = 85;
        int scienceMarks = 78;
        int englishMarks = 82;

        if (mathMarks >= 80) {
            if (scienceMarks >= 75) {
                if (englishMarks >= 70) {
                    System.out.println("Congratulations! You are eligible for admission.");
                } else {
                    System.out.println("Your English marks are below the required threshold.");
                }
            } else {
                System.out.println("Your Science marks are below the required threshold.");
            }
        } else {
            System.out.println("Your Math marks are below the required threshold.");
        }
    }
}

The switch Statement

The switch statement is an alternative to if-else-if ladder when you need to test a variable against multiple values. It's more efficient and readable for certain scenarios.

Syntax

switch (expression) {
    case value1:
        // code to be executed if expression == value1
        break;
    case value2:
        // code to be executed if expression == value2
        break;
    // more cases...
    default:
        // code to be executed if expression doesn't match any case
        break;
}

switch Statement Example

public class SwitchStatement {
    public static void main(String[] args) {
        int dayOfWeek = 3;

        switch (dayOfWeek) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid day");
                break;
        }

        // Another example: Calculator
        char operator = '+';
        double num1 = 10.5, num2 = 5.2, result = 0;

        switch (operator) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                if (num2 != 0) {
                    result = num1 / num2;
                } else {
                    System.out.println("Division by zero!");
                    return;
                }
                break;
            default:
                System.out.println("Invalid operator");
                return;
        }

        System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
    }
}

Switch with Strings (Java 7+)

Starting from Java 7, you can use strings in switch statements.

String switch Example

public class StringSwitch {
    public static void main(String[] args) {
        String fruit = "apple";

        switch (fruit.toLowerCase()) {
            case "apple":
                System.out.println("Apples are red or green.");
                break;
            case "banana":
                System.out.println("Bananas are yellow.");
                break;
            case "orange":
                System.out.println("Oranges are orange.");
                break;
            case "grape":
                System.out.println("Grapes can be purple or green.");
                break;
            default:
                System.out.println("Unknown fruit.");
                break;
        }

        // Another example: Month name to number
        String month = "March";
        int monthNumber = 0;

        switch (month) {
            case "January": monthNumber = 1; break;
            case "February": monthNumber = 2; break;
            case "March": monthNumber = 3; break;
            case "April": monthNumber = 4; break;
            case "May": monthNumber = 5; break;
            case "June": monthNumber = 6; break;
            case "July": monthNumber = 7; break;
            case "August": monthNumber = 8; break;
            case "September": monthNumber = 9; break;
            case "October": monthNumber = 10; break;
            case "November": monthNumber = 11; break;
            case "December": monthNumber = 12; break;
            default:
                System.out.println("Invalid month name");
                return;
        }

        System.out.println(month + " is month number " + monthNumber);
    }
}

Enhanced Switch Expression (Java 14+)

Java 14 introduced switch expressions, which are more concise and can return values directly.

Enhanced Switch Example

public class EnhancedSwitch {
    public static void main(String[] args) {
        int day = 3;

        // Traditional switch statement
        String dayName = "";
        switch (day) {
            case 1: dayName = "Monday"; break;
            case 2: dayName = "Tuesday"; break;
            case 3: dayName = "Wednesday"; break;
            case 4: dayName = "Thursday"; break;
            case 5: dayName = "Friday"; break;
            case 6: dayName = "Saturday"; break;
            case 7: dayName = "Sunday"; break;
            default: dayName = "Invalid day"; break;
        }
        System.out.println("Traditional switch: " + dayName);

        // Enhanced switch expression (Java 14+)
        String dayNameNew = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6 -> "Saturday";
            case 7 -> "Sunday";
            default -> "Invalid day";
        };
        System.out.println("Enhanced switch: " + dayNameNew);

        // Enhanced switch with multiple statements
        String dayType = switch (day) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Invalid";
        };
        System.out.println("Day type: " + dayType);
    }
}

Branching Statements

Branching statements allow you to transfer control to another part of the program.

The break Statement

The break statement is used to exit from a loop or switch statement prematurely.

public class BreakStatement {
    public static void main(String[] args) {
        // break in switch
        int number = 3;
        switch (number) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
            case 3:
                System.out.println("Three");
                break; // exits the switch
            case 4:
                System.out.println("Four");
                break;
        }

        // break in loop (will be covered in next tutorial)
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break; // exits the loop when i == 5
            }
            System.out.println("i = " + i);
        }
    }
}

The continue Statement

The continue statement skips the current iteration of a loop and continues with the next iteration.

public class ContinueStatement {
    public static void main(String[] args) {
        // continue in loop (will be covered in next tutorial)
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue; // skips even numbers
            }
            System.out.println("Odd number: " + i);
        }
    }
}

The return Statement

The return statement is used to exit from a method and optionally return a value.

public class ReturnStatement {
    public static void main(String[] args) {
        System.out.println("Maximum of 10 and 20: " + findMax(10, 20));
        checkEligibility(15);
        System.out.println("This won't be printed if age < 18");
    }

    public static int findMax(int a, int b) {
        if (a > b) {
            return a;
        } else {
            return b;
        }
    }

    public static void checkEligibility(int age) {
        if (age < 18) {
            System.out.println("Not eligible");
            return; // exits the method
        }
        System.out.println("Eligible");
    }
}

Practical Examples

Let's look at some practical examples that demonstrate the use of control flow statements:

public class ControlFlowExamples {
    public static void main(String[] args) {
        // Example 1: BMI Calculator
        double weight = 70; // kg
        double height = 1.75; // meters

        double bmi = weight / (height * height);

        if (bmi < 18.5) {
            System.out.println("Underweight");
        } else if (bmi < 25) {
            System.out.println("Normal weight");
        } else if (bmi < 30) {
            System.out.println("Overweight");
        } else {
            System.out.println("Obese");
        }

        // Example 2: Grade Calculator
        int score = 87;
        char grade;

        if (score >= 90) {
            grade = 'A';
        } else if (score >= 80) {
            grade = 'B';
        } else if (score >= 70) {
            grade = 'C';
        } else if (score >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }

        System.out.println("Score: " + score + ", Grade: " + grade);

        // Example 3: Menu-driven program
        int choice = 2;

        switch (choice) {
            case 1:
                System.out.println("You selected: View Balance");
                break;
            case 2:
                System.out.println("You selected: Deposit Money");
                break;
            case 3:
                System.out.println("You selected: Withdraw Money");
                break;
            case 4:
                System.out.println("You selected: Transfer Money");
                break;
            default:
                System.out.println("Invalid choice");
        }

        // Example 4: Authentication system
        String username = "admin";
        String password = "password123";
        boolean isValidUser = false;

        if (username.equals("admin")) {
            if (password.equals("password123")) {
                isValidUser = true;
            }
        }

        if (isValidUser) {
            System.out.println("Login successful!");
        } else {
            System.out.println("Invalid credentials!");
        }

        // Example 5: Number classification
        int num = -15;

        if (num > 0) {
            if (num % 2 == 0) {
                System.out.println(num + " is positive and even");
            } else {
                System.out.println(num + " is positive and odd");
            }
        } else if (num < 0) {
            System.out.println(num + " is negative");
        } else {
            System.out.println(num + " is zero");
        }
    }
}

Best Practices

When using control flow statements in Java:

  • Use if-else statements for simple conditions and switch for multiple discrete values
  • Avoid deeply nested if statements - consider refactoring into methods
  • Always use break statements in switch cases to prevent fall-through
  • Use meaningful variable names and comments for complex conditions
  • Consider using switch expressions (Java 14+) for cleaner code
  • Use early returns to reduce nesting and improve readability
  • Test all branches of your conditional logic
  • Avoid using floating-point numbers in switch statements (use if-else instead)
  • Use the ternary operator for simple conditional assignments
  • Consider using enums with switch statements for better type safety

Control flow statements are fundamental to programming logic. They allow your programs to make decisions and respond differently based on various conditions, making your code more intelligent and responsive.