Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Control statements in Java

Control statements in Java: sequence, selection (if, if–else, switch), iteration (while, do–while, for, enhanced for), and jump statements (break, continue, return, labels) with syntax, rules, and examples.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Control statements decide which statements run, how many times, and in what order. In real systems (billing, sensor monitoring, UI flows), engineers use control statements to implement business rules, loop over data, skip invalid inputs, and stop early when a goal is achieved.

Key ideas

  • Sequential execution: Statements run line by line with no branching. This is the base case for control flow.
  • Selection (branching): Choose between alternatives based on a Boolean condition. Java provides:
    • if statement: Executes a block only if a condition is true.
    • if–else statement: Executes one block if condition is true, otherwise another block.
    • Nested if: An if (or if–else) inside another if (or else) block; used for multi-level decisions.
    • if–else ladder: Multiple conditions evaluated in order; the first true condition’s block runs, and the rest are skipped.
    • switch statement: Selects one case to execute based on the value of a single expression, with optional fall-through. Useful when comparing the same expression to many fixed options.
    • conditional operator (?:): A ternary operator that selects between two expressions based on a boolean condition: result = condition ? exprIfTrue : exprIfFalse;
  • Iteration (looping): Repeat a block while a condition is true or for a fixed number of times.
    • while loop: Pre-test loop; executes zero or more times.
    • do–while loop: Post-test loop; executes at least once, then repeats while condition is true.
    • for loop: Compact loop with initializer, condition, and updater; suited for counted loops.
    • Enhanced for loop (for-each): Iterates over arrays and Iterable collections directly, in the collection’s iteration order.
  • Jump statements: Change the normal progression within loops or methods.
    • break: Exits the nearest enclosing switch or loop immediately.
    • continue: Skips to the next iteration of the nearest enclosing loop.
    • return: Exits the current method, optionally returning a value.
    • Labeled break/continue: Apply break/continue to an outer loop using a label.
  • Boolean condition: Java requires conditions in if/while/do–while/for to be of type boolean. There is no implicit conversion from integers to boolean (unlike C/C++). Use comparison operators (==, !=, <, >, <=, >=) and logical operators (&&, ||, !).

Definitions, assumptions, and exact statements commonly asked:

  • Definition: if statement — Executes a statement or block only when its boolean condition evaluates to true. Assumes the condition is a boolean expression.
  • Definition: if–else statement — Chooses exactly one of two blocks based on a boolean condition; if the condition is true, executes the if-block, otherwise executes the else-block.
  • Definition: switch statement — A multi-way branch that compares the value of a switch expression to compile-time constant case labels. On matching a case, execution starts there and continues until a break, return, or the end of the switch. If no case matches, the optional default block executes.
    • Law/Rule: Case labels must be constant expressions, unique within a switch, and type-compatible with the switch expression.
    • Rule: In traditional switch statements, control falls through to the next case if there is no break at the end of a case block.
  • Definition: while loop — Repeats the loop body while the boolean condition is true; condition is tested before each iteration. Zero or more iterations.
  • Definition: do–while loop — Executes the loop body once, then repeats while the boolean condition is true; condition is tested after each iteration. One or more iterations.
  • Definition: for loop — A counted loop with three parts: initialization (executed once), condition (tested before each iteration), and update (executed after each iteration). Zero or more iterations.
  • Definition: enhanced for loop — Syntactic sugar for iteration over arrays and objects that implement Iterable; automatically retrieves each element in order.
  • Definition: break — Transfers control to the statement after the enclosing loop or switch (or to the end of a labeled statement if labeled break is used).
  • Definition: continue — Transfers control to the loop’s next iteration: in a for loop, the update expression runs first, then the condition is re-checked; in a while loop, the condition is re-checked; in a do–while loop, control jumps to the condition at the end of the loop (there is no separate update location).
  • Definition: return — Exits the current method immediately, optionally returning a value if the method’s return type is not void.

Type rules and constraints often examined:

  • If/while/do–while/for conditions must be boolean (true/false). Numeric types cannot act as booleans.
  • switch expression types include: byte, short, char, int (and their wrappers), enums, and String. long, float, double, and boolean are not permitted in a classic switch. Case labels must be compile-time constants of a compatible type.
  • Scope: Variables declared in the for initializer or inside loop blocks are local to that block and not visible outside.
  • Labeled statements: A valid Java identifier followed by a colon can label a statement (commonly a loop). break label; exits that labeled statement. continue label; proceeds to the next iteration of the labeled loop.

Common derivations/reasoning universities ask:

  • Prove/argue “do–while executes at least once”: In do–while, the body is executed before the condition is checked; thus one execution is guaranteed regardless of the initial condition value.
  • Show “switch fall-through behavior”: Without break, once a matching case is found, subsequent cases execute until a break or the switch ends, leading to multiple case bodies running.

What to draw and label (when asked for a flowchart):

  • For if–else: Start → Evaluate condition? → True branch executes Block A → Merge → End; False branch executes Block B → Merge → End. Label the diamond node as the condition and the two arrows as true/false.
  • For while: Start → Initialize → Condition? → True → Body → Update → back to Condition; False → Exit loop → End. Make sure to mark “pre-test”.
  • For do–while: Start → Body → Condition? → True → back to Body; False → Exit loop → End. Mark “post-test” and “executes at least once”.

Notes on advanced switch (for context): Some newer Java versions add switch expressions and pattern matching. For exam-focused core understanding, master the classic switch statement with break/default and constant case labels.

Formulas

if (condition) statement; if (condition) { statements }

  • if–else if (condition) { statements } else { statements }
  • if–else ladder if (cond1) { ... } else if (cond2) { ... } else { ... }
  • nested if if (condA) { if (condB) { ... } else { ... } }
  • switch (classic) switch (expression) { case CONST1: statements; break; case CONST2: statements; break; default: statements; }
  • while while (condition) { statements }
  • do–while do { statements } while (condition);
  • for (classic) for (init; condition; update) { statements }
  • for (multiple init/update) for (int i = 0, j = n; i < j; i++, j--) { ... }
  • enhanced for (for-each) for (ElementType x : collectionOrArray) { use x }
  • break and continue break; continue;
  • labeled break/continue labelName: for (...) { for (...) { if (cond) break labelName; } } labelName: while (...) { if (cond) continue labelName; }
  • return return; (in void methods) return expression; (expression type must match method return type)

Worked examples

Example 1: if–else ladder for grading Program: Reads an integer mark (0–100) and prints grade.

import java.util.Scanner;

public class GradeCalculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter marks (0-100): ");
        int marks = sc.nextInt();

        if (marks < 0 || marks > 100) {
            System.out.println("Invalid marks");
        } else 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");
        }
    }
}

Sample input:

86

Exact output:

Enter marks (0-100): Grade: A

Example 2: switch-based calculator (classic switch with break) Program: Reads an operator and two numbers; performs +, -, *, or / with basic divide-by-zero check.

import java.util.Scanner;

public class SwitchCalculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter operator (+, -, *, /): ");
        char op = sc.next().charAt(0);
        System.out.print("Enter first number: ");
        double a = sc.nextDouble();
        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        switch (op) {
            case '+':
                System.out.println("Result: " + (a + b));
                break;
            case '-':
                System.out.println("Result: " + (a - b));
                break;
            case '*':
                System.out.println("Result: " + (a * b));
                break;
            case '/':
                if (b == 0.0) {
                    System.out.println("Error: Division by zero");
                } else {
                    System.out.println("Result: " + (a / b));
                }
                break;
            default:
                System.out.println("Unknown operator");
        }
    }
}

Sample input:

+
12.5
7.5

Exact output:

Enter operator (+, -, *, /): Enter first number: Enter second number: Result: 20.0

Example 3: loops, continue, and labeled break Program: Finds the first prime number greater than or equal to a given n using nested loops. Demonstrates continue and labeled break.

import java.util.Scanner;

public class FirstPrimeFromN {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n (>=2): ");
        int n = sc.nextInt();
        if (n < 2) {
            System.out.println("Input must be >= 2");
            return; // exits main
        }

        int candidate = n;
        search: while (true) { // labeled loop
            if (candidate % 2 == 0 && candidate != 2) {
                candidate++;
                continue; // skip even numbers > 2
            }
            boolean isPrime = true;
            for (int d = 3; d * d <= candidate; d += 2) { // test odd divisors only
                if (candidate % d == 0) {
                    isPrime = false;
                    candidate++;
                    continue search; // try next candidate
                }
            }
            // If we reach here, no divisor found
            System.out.println("First prime >= " + n + " is " + candidate);
            break; // or break search;
        }
    }
}

Sample input:

24

Exact output:

Enter n (>=2): First prime >= 24 is 29

Notes on the examples:

  • Example 1 shows an if–else ladder and strict boolean conditions.
  • Example 2 shows switch with break, a default case, and input reading with Scanner (see “Console input and output with streams” topic for more on I/O).
  • Example 3 demonstrates while, for, continue, labeled continue, and break. The for loop’s condition uses d * d <= candidate to avoid floating-point sqrt.

Common mistakes

  • Forgetting break in switch cases, causing unintended fall-through. If intentional fall-through is used, add a comment to show intent.
  • Using non-constant or non-unique case labels in switch. Each case must be a compile-time constant and distinct within the switch.
  • Switching on an unsupported type (e.g., long). Use int-range types, char, String, or enums instead.
  • Off-by-one errors in loops (wrong start or end condition). Carefully decide whether to use <, <=, >, or >=.
  • Dangling else: else attaches to the nearest unmatched if; always use braces to make intent explicit.
  • Infinite loops due to missing or incorrect update (e.g., forgetting i++ in for/while).
  • Misunderstanding do–while; expecting zero iterations. do–while runs at least once.
  • Using continue or break with the wrong label or outside of a loop/switch. continue cannot be used with switch directly; it applies to loops. break can exit a switch or loop.
  • Variable scope confusion: Using a loop variable declared in for outside the loop.
  • Modifying a collection while iterating with enhanced for without using an Iterator; leads to ConcurrentModificationException (relevant when using Java collections).

For your exam

  • Short notes: Differences between while and do–while; switch vs if–else ladder; fall-through; scope of loop variables; labeled vs unlabeled break/continue; enhanced for limitations (no index, read-only iteration variable).
  • Diagrams: Flowcharts for if–else, while, and do–while. Draw clear start/end, diamond for condition, arrows labeled true/false, and loop-back arrows. Mention pre-test vs post-test explicitly.
  • Programs: Write a menu-driven program using switch (with break and default). Write loops for factorial, prime checking, Fibonacci, or summing array elements with enhanced for. Always include input, validation, and output formatting.
  • Tracing: Given a snippet with nested loops, indicate iteration counts, variable values, and output. Show a table of i, j per iteration to score full marks.
  • Reasoning: Explain why do–while executes at least once; explain fall-through and how break prevents it; explain why switch cannot use long and why case labels must be constants.
  • Best-practice points that fetch credit: Use braces consistently, include default in switch, avoid magic numbers (use named constants), validate inputs, and comment intentional fall-through.

Quick check

  1. State one key difference between while and do–while.
  2. List any four types allowed in a classic switch expression.
  3. What does continue do in a for loop, and what executes immediately after it?

Answers: 1) while is pre-test and may execute zero times; do–while is post-test and executes at least once. 2) byte, short, char, int, String, enum (any four). 3) Skips the remaining body of the current iteration; then the for loop’s update expression runs (if any), followed by re-evaluating the loop condition.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?