Skip to main content

Control Flow

Conditional Control Statements

Complete lesson for Conditional Control Statements using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Conditional Control Statements

Section: Control Flow. if, if-else, else-if ladder, nested if, classic switch, Java 14+ switch expressions, and ternary — with flowcharts and real-life examples.

What are conditional statements?

  • Conditional (decision-making) statements let a program choose different code paths based on a boolean condition.
  • Main forms: if, if-else, else if ladder, nested if, classic switch, switch expressions (Java 14+), and the ternary operator ?:.
  • Unlike C/C++, Java does not treat numbers as true/false. if (x) for an int does not compile — write if (x != 0) if that is what you mean.
  • Use the flowchart image below to see how control flows for each if-style statement.

Flowcharts: if, if-else, else-if & nested if

Decision-making statements choose different Java blocks when a boolean condition is true. The diagram below shows flowcharts, syntax, and short examples for if, if-else, else-if ladder, and nested if.

Flowcharts of if, if-else, else-if ladder, and nested if in Java with syntax and System.out.println examples for each decision structure.
Java if-statement flowcharts — choose the right decision structure for your requirement
  • if: run a block only when the condition is true.
  • if-else: choose between two opposite outcomes.
  • else-if ladder: check multiple ordered conditions (grades, fares).
  • nested if: a second check that depends on the first (login then checkout).

if statement

  • Runs a block only when the condition is true; otherwise that block is skipped and the program continues.
  • Real-life example: ATM cash withdrawal — if balance is enough, allow withdraw; if not, skip this simple check.
  • Real-life example: Phone unlock — if the PIN is correct, open the home screen.
PartMeaningReal-life mapping
if (condition)Test a yes/no booleanIs balance >= amount?
True blockDo the actionDispense cash
No elseSkip when falseStay on the same screen
public class IfOnly {
    public static void main(String[] args) {
        int balance = 5000;
        int amount = 2000;
        if (balance >= amount) {
            System.out.println("Withdrawal allowed");
        }
    }
}

if-else statement

  • Chooses exactly one of two paths: the true block or the false (else) block.
  • Real-life example: Exam result — if marks >= 40 print Pass, else print Fail.
  • Real-life example: Traffic light (simplified) — if the light is green, go; else stop.
public class IfElsePass {
    public static void main(String[] args) {
        int marks = 35;
        if (marks >= 40) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
    }
}

else if ladder

  • Checks conditions in order; the first true condition runs, then the ladder stops.
  • Real-life example: Grading system — A / B / C / Fail based on marks ranges.
  • Real-life example: Ticket pricing — child / adult / senior fares based on age.
public class GradeLadder {
    public static void main(String[] args) {
        int marks = 85;
        if (marks >= 90) {
            System.out.println("Grade A");
        } else if (marks >= 75) {
            System.out.println("Grade B");
        } else if (marks >= 50) {
            System.out.println("Grade C");
        } else {
            System.out.println("Fail");
        }
    }
}

Nested if statement

  • An if inside another if — use it when a second check depends on the first.
  • Real-life example: Online order — if logged in, then if the cart is not empty, place the order.
  • Real-life example: Loan check — if salary is high enough, then if credit score is good, approve.
public class NestedIfOrder {
    public static void main(String[] args) {
        boolean loggedIn = true;
        int cartItems = 3;
        if (loggedIn) {
            if (cartItems > 0) {
                System.out.println("Order placed");
            } else {
                System.out.println("Cart is empty");
            }
        } else {
            System.out.println("Please log in");
        }
    }
}

Classic switch (statement)

  • Selects among many fixed choices of one discrete value. Selector types: byte, short, char, int and their wrappers, String (Java 7+), and enums.
  • long, float, double, and boolean cannot be switch selectors — use if/else for those.
  • Without break, execution falls through to the next case — usually a bug, sometimes intentional.
  • Real-life example: Food-court menu — case 1 Pizza, case 2 Burger, case 3 Pasta, default Invalid.
public class MenuSwitch {
    public static void main(String[] args) {
        int choice = 2;
        switch (choice) {
            case 1:
                System.out.println("Pizza");
                break;
            case 2:
                System.out.println("Burger");
                break;
            case 3:
                System.out.println("Pasta");
                break;
            default:
                System.out.println("Invalid choice");
        }
    }
}

Switch expressions (Java 14+)

  • Arrow cases (case 1 ->) do not fall through. A switch can produce a value you assign to a variable.
  • yield is used inside a block case to produce the value. default is required for an expression unless the enum is exhaustive.
  • Comma-separated labels (case "SAT", "SUN" ->) share one arrow body.
StyleFall-throughProduces a value?
switch statement + breakYes, if you omit breakNo (side effects only)
switch expression + ->NoYes
switch expression + { } / yieldNoYes
public class DayType {
    public static void main(String[] args) {
        String day = "SAT";
        String kind = switch (day) {
            case "SAT", "SUN" -> "weekend";
            case "MON", "TUE", "WED", "THU", "FRI" -> "weekday";
            default -> "unknown";
        };
        System.out.println(kind);
    }
}

Ternary operator (quick form)

  • Compact if-else that yields a value: condition ? valueIfTrue : valueIfFalse. Both branches must be assignment-compatible.
  • Real-life example: Display Open or Closed for a shop based on the current hour.
public class ShopHours {
    public static void main(String[] args) {
        int hour = 22;
        String status = (hour >= 9 && hour < 21) ? "Open" : "Closed";
        System.out.println(status);
    }
}

Which statement should you use?

  • Pick the form that matches your decision shape — keep the code readable.
SituationBest choiceReal-life example
One optional actionifShow a low-battery warning only when needed
Two opposite outcomesif-elsePass / Fail
Many ranges / ordered checkselse if ladderGrades, ticket age bands
Decision inside another decisionNested ifLogin then checkout
Many fixed discrete optionsswitchMenu / keypad / day of week
Simple value choiceTernary ?:Open / Closed label
L2

Advanced — Conditional Control Statements

Deeper rules for if / else if / nested if

  • The condition must be boolean (or Boolean). Non-zero integers are not automatically true.
  • Brace every block { } even for one line — that kills dangling-else bugs (else always binds to the nearest unmatched if).
  • Order matters in an else-if ladder: put more specific / higher-priority checks first (>= 90 before >= 75).
  • Prefer early return in methods instead of deep nesting when it improves clarity.
  • if (x = 5) does not compile: assignment of int is not a boolean. Use == for comparison.
public class DanglingElse {
    public static void main(String[] args) {
        int n = 4;
        if (n > 0) {
            if (n % 2 == 0) {
                System.out.println("positive even");
            } else {
                System.out.println("positive odd");
            }
        } else {
            System.out.println("non-positive");
        }
    }
}

switch in depth and pattern matching

  • case labels must be compile-time constants (literals, final constants, enum constants).
  • Classic switch: stack labels to share a body (case 6: case 7:). Arrow switch: case 6, 7 ->.
  • Java 16+ pattern matching: if (obj instanceof String s) binds s only when the test succeeds.
  • Java 21 adds switch pattern matching and record patterns; many interviews still start with classic + arrow switch.
  • For ranges (marks >= 90), prefer else-if. Switch is best for exact matches.
public class YieldSwitch {
    static String band(int marks) {
        return switch (marks / 10) {
            case 10, 9 -> "A";
            case 8, 7 -> {
                yield "B";
            }
            case 6, 5 -> "C";
            default -> "Fail";
        };
    }

    public static void main(String[] args) {
        Object obj = "Java";
        if (obj instanceof String s) {
            System.out.println(s.length());
        }
        System.out.println(band(85));
    }
}

Real-life decision models (combined)

  • ATM: nested checks — card valid, then PIN correct, then balance enough, then dispense.
  • E-commerce coupon: else-if ladder on cart total for discount slabs.
  • Elevator panel / keypad: switch on button number.
  • Weather app: if raining and temperature < 10, print Carry umbrella and jacket.
  • Day type: switch expression on a String day code to weekend / weekday.
L3

Tricky Interview Points

Q1) What is a conditional statement in Java?

Answer A statement that chooses which code to run based on a boolean condition: if, if-else, else-if, nested if, switch, switch expressions, and ternary.

Q2) Can you write if (1) in Java?

Answer No. The condition must be boolean. if (1) is a C/C++ habit and does not compile. Write if (x != 0) when you mean a non-zero int.

Q3) Difference between if and if-else?

Answer if runs a block only when true and otherwise skips it. if-else always chooses one of two blocks: true or false.

Q4) What is an else-if ladder?

Answer A chain of if / else if / else checks evaluated in order. The first true condition’s block runs, then the chain stops.

Q5) What is a nested if?

Answer An if statement placed inside another if/else block. Used when a second decision depends on the first (for example login then checkout).

Q6) When should you use switch instead of if-else?

Answer When branching on one discrete value with many exact matches (menu choice, day number, enum, String code). For ranges, else-if is usually clearer.

Q7) Which types work in a switch?

Answer byte, short, char, int (and wrappers), String, and enum. Not long, float, double, or boolean.

Q8) What is fall-through?

Answer In a classic switch, after a matching case, execution continues into later cases until break, return, or the end.

Q9) What did Java 14 add for switch?

Answer Switch expressions: arrow cases without fall-through, comma-separated labels, and the ability to return a value (yield in block cases).

Q10) Is default mandatory?

Answer For a switch statement, no. For a switch expression, yes — unless the compiler can prove every enum constant is covered.

Q11) Can two cases share a body?

Answer Yes. Classic: stacked case labels. Arrow switch: case 1, 2, 3 -> ...

Q12) What is a dangling else?

Answer Ambiguity about which if an else belongs to when braces are missing. Always use { } to make pairing clear.

Q13) What is the ternary operator?

Answer condition ? exprTrue : exprFalse — a compact expression form of if-else that yields a value.

Q14) What does if (obj instanceof String s) do?

Answer Pattern matching for instanceof (Java 16+): if obj is a String, s is bound to that String in the true block. null instanceof String is false.

L4

Simple Programs

if — low balance warning

public class LowBalance {
    public static void main(String[] args) {
        int balance = 300;
        if (balance < 500) {
            System.out.println("Low balance warning");
        }
    }
}

if-else — even or odd

public class EvenOdd {
    public static void main(String[] args) {
        int n = 17;
        if (n % 2 == 0) {
            System.out.println("Even");
        } else {
            System.out.println("Odd");
        }
    }
}

else-if — ticket fare by age

public class TicketFare {
    public static void main(String[] args) {
        int age = 14;
        if (age < 5) {
            System.out.println("Free");
        } else if (age < 18) {
            System.out.println("Child fare");
        } else if (age < 60) {
            System.out.println("Adult fare");
        } else {
            System.out.println("Senior fare");
        }
    }
}

Nested if — login then order

public class Checkout {
    public static void main(String[] args) {
        boolean loggedIn = true;
        int cart = 2;
        if (loggedIn) {
            if (cart > 0) {
                System.out.println("Checkout OK");
            } else {
                System.out.println("Add items first");
            }
        } else {
            System.out.println("Login required");
        }
    }
}

Classic switch with break

public class ClassicSwitch {
    public static void main(String[] args) {
        int n = 2;
        switch (n) {
            case 1:
                System.out.println("one");
                break;
            case 2:
                System.out.println("two");
                break;
            default:
                System.out.println("other");
        }
    }
}

Switch expression (Java 14+)

public class DayTypeExpr {
    public static void main(String[] args) {
        String day = "SAT";
        String kind = switch (day) {
            case "SAT", "SUN" -> "weekend";
            case "MON", "TUE", "WED", "THU", "FRI" -> "weekday";
            default -> "unknown";
        };
        System.out.println(kind);
    }
}

Ternary — shop open or closed

public class ShopOpen {
    public static void main(String[] args) {
        int hour = 20;
        String s = (hour >= 9 && hour < 21) ? "Open" : "Closed";
        System.out.println(s);
    }
}
L5

Problem Solving Tricks

  • Always use braces { } with if/else — prevents dangling-else mistakes.
  • Java conditions are boolean-only; never write if (n) for an int.
  • In else-if ladders, order ranges from high to low (or most specific first).
  • Prefer else if for ranges; prefer switch for exact menu-like choices.
  • Put break after every classic switch case unless fall-through is intentional and commented.
  • Prefer arrow switch when you only need a value — no forgotten break.
  • Switch on enums instead of magic strings when the set is closed.
  • Keep nested if depth small; extract helper methods when nesting gets hard to read.
  • Use ternary only for short value choices — not for multi-statement logic.
  • Test boundary values in grades/fares (exactly 40, 75, 90) — off-by-one bugs hide there.
  • Put the boolean test first in x != null && x.method() so the method never runs on null.
L6

Practice Programs List

  1. Write an if program that prints Eligible to vote only when age >= 18.
  2. Write if-else to check whether a year is a leap year (4 / 100 / 400 rule).
  3. Build an else-if grade calculator that also prints Pass/Fail.
  4. Write nested if for ATM: valid PIN, then sufficient balance, then success message.
  5. Create a switch calculator menu: 1 add, 2 sub, 3 mul, 4 div of two integers.
  6. Use switch on a char traffic light: R stop, Y wait, G go.
  7. Rewrite a Pass/Fail if-else using the ternary operator.
  8. Write else-if for electricity bill slabs based on units consumed.
  9. Nested if: if temperature > 30 and humidity > 70 print Humid heat warning.
  10. Map marks 0–100 to letter grades with else if, then rewrite as a switch expression over marks / 10.
  11. Write a classic switch that intentionally falls through (days in a month) and comment why.
  12. Use instanceof pattern matching to print the length if an Object is a String.