LearnFrenzy
Sign in Take a free test

Java Programming · Topic 3 of 28

Control Flow Statements

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Control Flow Statements · Study material

Control flow in Java decides which statements run, how often and in what order. Every real program – checking a login, calculating a bill, processing a list of orders, searching for a value – is built from three ideas: decisions (if, switch), loops (for, while, do-while, for-each) and jumps (break, continue, return). Modern Java adds switch expressions (Java 14) and pattern matching for switch (Java 21), which make decision logic shorter and safer. Pattern printing, number programs and "how many times does this loop run?" questions are a staple of campus placement tests, so this topic is essential practice. Then test yourself with 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all compiled and run on Java 21.

On this page

  • if, else-if ladders and guard clauses
  • The classic switch statement and fall-through
  • Switch expressions with arrows and yield
  • Pattern matching for switch with guards (Java 21)
  • while, do-while, for and enhanced for loops
  • break, continue and labelled jumps

if, else if and else

An if runs its block when the condition – which must be a boolean – is true. Chain alternatives with else if; at most one branch runs, the first whose condition holds. Always use braces, even for one statement: it prevents the "dangling else" and the bug of adding a second line that is not actually inside the if.

public class Main {
    static String grade(int marks) {
        if (marks < 0 || marks > 100) {
            return "invalid";
        } else if (marks >= 90) {
            return "A+";
        } else if (marks >= 75) {
            return "A";
        } else if (marks >= 60) {
            return "B";
        } else if (marks >= 35) {
            return "C";
        } else {
            return "Fail";
        }
    }

    public static void main(String[] args) {
        for (int m : new int[]{95, 75, 61, 35, 20, 120}) System.out.print(m + ":" + grade(m) + " ");
        System.out.println();
    }
}

Output

95:A+ 75:A 61:B 35:C 20:Fail 120:invalid

The classic switch statement

A switch compares one value (int and smaller types, char, String, an enum, or their wrappers) against case labels. Execution jumps to the matching label and falls through into the following cases until a break – handy for grouping labels, but a common source of bugs. default handles everything else.

public class Main {
    public static void main(String[] args) {
        for (int month : new int[]{2, 4, 7, 13}) {
            int days;
            switch (month) {
                case 2:
                    days = 28;
                    break;
                case 4: case 6: case 9: case 11:      // several labels share one body
                    days = 30;
                    break;
                case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                    days = 31;
                    break;
                default:
                    days = -1;
            }
            System.out.print(month + "->" + days + " ");
        }
        System.out.println();

        // Without break, execution FALLS THROUGH into the next case
        int level = 2;
        switch (level) {
            case 1: System.out.print("bronze ");
            case 2: System.out.print("silver ");
            case 3: System.out.print("gold ");
        }
        System.out.println();
    }
}

Output

2->28 4->30 7->31 13->-1
silver gold

Switch expressions (Java 14)

With case X -> there is no fall-through, several labels can share one arm (case SAT, SUN ->), and the switch can produce a value. A block arm returns its value with yield. A switch expression must be exhaustive: it needs a default unless it covers every enum constant (or every permitted subtype of a sealed type).

public class Main {
    enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

    public static void main(String[] args) {
        // Switch EXPRESSION (Java 14): arrows, no fall-through, produces a value
        for (Day d : new Day[]{Day.MON, Day.SAT, Day.WED}) {
            String type = switch (d) {
                case SAT, SUN -> "weekend";
                case MON, TUE, WED, THU, FRI -> "weekday";     // exhaustive: no default needed for an enum
            };
            int hours = switch (d) {
                case SAT, SUN -> 0;
                case FRI -> 6;
                default -> {
                    int base = 8;
                    yield base + 1;                            // yield returns a value from a block
                }
            };
            System.out.println(d + " " + type + " " + hours);
        }

        String cmd = "stop";
        System.out.println(switch (cmd) {
            case "start" -> "starting";
            case "stop" -> "stopping";
            default -> "unknown";
        });
    }
}

Output

MON weekday 9
SAT weekend 0
WED weekday 9
stopping

Pattern matching for switch (Java 21)

A switch can now test the type of a value, bind it to a variable, deconstruct records (case Circle(double r)), add conditions with when guards and handle case null. More specific cases must come before more general ones.

public class Main {
    sealed interface Shape permits Circle, Square, Rect {}
    record Circle(double r) implements Shape {}
    record Square(double side) implements Shape {}
    record Rect(double w, double h) implements Shape {}

    // Java 21: switch on types, with record patterns and guards (when)
    static String describe(Object o) {
        return switch (o) {
            case null -> "null";
            case Integer i when i > 100 -> "big int " + i;
            case Integer i -> "int " + i;
            case String s when s.isBlank() -> "blank string";
            case String s -> "string of " + s.length();
            case Circle(double r) -> "circle area " + Math.round(Math.PI * r * r);
            case Shape s -> "some other shape: " + s;
            default -> "other " + o.getClass().getSimpleName();
        };
    }

    public static void main(String[] args) {
        Object[] items = {7, 250, " ", "Java", new Circle(2), new Square(3), 4.5, null};
        for (Object o : items) System.out.println(describe(o));
    }
}

Output

int 7
big int 250
blank string
string of 4
circle area 13
some other shape: Square[side=3.0]
other Double
null

Loops: while, do-while, for and for-each

LoopChecks the conditionUse when
while (cond) { … }before each iteration (may run 0 times)the number of iterations is not known in advance
do { … } while (cond);after each iteration (runs at least once)menus, input validation, "try at least once"
for (init; cond; update)before each iterationcounting loops with an index
for (T x : collection)–visiting every element of an array or collection
public class Main {
    public static void main(String[] args) {
        // while: check first – may run zero times
        int n = 1234, digits = 0;
        while (n > 0) { n /= 10; digits++; }

        // do-while: runs at least once
        int tries = 0, value = 50;
        do { value -= 20; tries++; } while (value > 0);

        // for: initialise; condition; update
        long factorial = 1;
        for (int i = 2; i <= 10; i++) factorial *= i;

        // enhanced for (for-each): every element, no index
        int sum = 0;
        for (int x : new int[]{4, 8, 15, 16, 23, 42}) sum += x;

        System.out.println(digits + " " + tries + " " + value + " " + factorial + " " + sum);

        // several variables in one for header
        for (int lo = 0, hi = 5; lo < hi; lo++, hi--) System.out.print("(" + lo + "," + hi + ")");
        System.out.println();
    }
}

Output

4 3 -10 3628800 108
(0,5)(1,4)(2,3)

break, continue and labels

break leaves the innermost loop or switch; continue skips the rest of the current iteration. With a label (outer:) you can break out of, or continue, an enclosing loop directly – the clean way to stop a nested search.

public class Main {
    public static void main(String[] args) {
        // continue skips to the next iteration; break leaves the loop
        for (int i = 1; i <= 10; i++) {
            if (i % 3 == 0) continue;
            if (i > 8) break;
            System.out.print(i + " ");
        }
        System.out.println();

        // A labelled break leaves the OUTER loop at once
        int[][] grid = {{1, 2, 3}, {4, -5, 6}, {7, 8, 9}};
        outer:
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] < 0) {
                    System.out.println("first negative at row " + r + ", col " + c);
                    break outer;
                }
            }
        }

        // A labelled continue moves to the next iteration of the OUTER loop
        rows:
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 3; c++) {
                if (c > r) continue rows;
                System.out.print(grid[r][c] + " ");
            }
        }
        System.out.println();
    }
}

Output

1 2 4 5 7 8
first negative at row 1, col 1
1 4 -5 7 8 9

Common mistakes

  • Missing break in a classic switch – the next case runs too.
  • A stray semicolon – if (x > 0); or for (…); makes the body empty.
  • Off-by-one loops – i <= arr.length throws ArrayIndexOutOfBoundsException.
  • Infinite loops – forgetting to update the loop variable in while.
  • Comparing Strings with == in conditions – use equals() (or switch on the String).
  • Modifying a collection inside for-each – ConcurrentModificationException.
  • Unreachable code after break, continue or return – javac rejects it.

Key points to remember

  • Conditions must be boolean; there is no implicit int → boolean conversion.
  • Classic switch falls through without break; arrow cases never do.
  • Switch expressions return values, use yield in blocks and must be exhaustive.
  • Java 21 switch matches types, records, guards (when) and null.
  • do-while runs at least once; while and for may run zero times.
  • Labelled break/continue control outer loops.

Frequently asked questions

Which types can a switch use?

Classic and arrow switches on values work with byte, short, char, int, their wrappers, String and enums. Pattern-matching switch (Java 21) works on any reference type. long, float, double and boolean cannot be switched on as values.

Is a switch faster than if-else?

For many constant cases the compiler can use a jump table or hash lookup, so a switch can be faster and is usually clearer; for two or three conditions it makes no difference.

Does Java have goto?

goto is a reserved word but has no meaning; labelled break and continue cover its legitimate uses.

Where can I learn more?

Read Java if-else and switch, Java Loops and Java break and continue, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links