⬅ Previous Next ➡

Control Flow Statements

Decision Making & Looping in Java (if, switch, for, while, do-while, break, continue, return, enhanced for)
  • Decision Making lets a program choose different paths based on conditions.
  • Loops repeat a block of code until a condition becomes false.
  • Below examples use sample student-style data like "Sourav", marks, attempts, and simple menu options (non-copyright).

1) if Statement

  • Executes a block only when the condition is true.
class IfDemo {
    public static void main(String[] args) {
        int marks = 78;

        if (marks >= 40) {
            System.out.println("Status: Pass");
        }
    }
}

2) if-else Statement

  • Runs if block when condition is true, otherwise runs else.
class IfElseDemo {
    public static void main(String[] args) {
        String studentName = "Sourav";
        int marks = 33;

        if (marks >= 40) {
            System.out.println(studentName + " is Pass");
        } else {
            System.out.println(studentName + " is Fail");
        }
    }
}

3) Nested if

  • An if inside another if for multi-level conditions.
class NestedIfDemo {
    public static void main(String[] args) {
        int marks = 86;

        if (marks >= 40) {
            if (marks >= 75) {
                System.out.println("Grade: Distinction");
            } else {
                System.out.println("Grade: Pass");
            }
        } else {
            System.out.println("Grade: Fail");
        }
    }
}

4) switch-case

  • Used when checking one variable against multiple values.
  • Use break to stop fall-through.
class SwitchDemo {
    public static void main(String[] args) {
        int choice = 2;

        switch (choice) {
            case 1:
                System.out.println("Selected: View Profile");
                break;
            case 2:
                System.out.println("Selected: Start Mock Test");
                break;
            case 3:
                System.out.println("Selected: View Result");
                break;
            default:
                System.out.println("Invalid Option");
        }
    }
}

5) for Loop

  • Best when number of iterations is known.
class ForLoopDemo {
    public static void main(String[] args) {
        for (int i = 1; i  0) {
            System.out.println("Attempts left: " + attemptsLeft);
            attemptsLeft--;
        }
    }
}

7) do-while Loop

  • Runs at least once (condition checked after execution).
class DoWhileDemo {
    public static void main(String[] args) {
        int otpTries = 0;

        do {
            otpTries++;
            System.out.println("OTP Try: " + otpTries);
        } while (otpTries < 2);
    }
}

8) break Statement

  • Stops the loop or switch immediately.
class BreakDemo {
    public static void main(String[] args) {
        for (int i = 1; i