Java + Spring Boot track

Lesson 04 · Part 1: Basics

Control Flow

The statement used to split or repeat the flow of code is a control flow. Java's control statements resemble C's, but modern forms such as switch expression in JDK…

Part 1: Basics4 min readFree lesson

The statement used to split or repeat the flow of code is a control flow. Java's control statements resemble C's, but modern forms such as switch expression in JDK 14+ are also used.

Learning Objectives

  • Uses if / else if / else structures
  • Learn the new switch expression (-> / yield) syntax
  • Know the difference between for, while, do-while, enhanced for
  • Know the meaning of break, continue, and label jumps

Key concepts

1) if / else if / else

int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C or lower");
}

2) Switch expression (JDK 14+)

int day = 3;
String name = switch (day) {
    case 1, 2, 3, 4, 5 -> "weekdays";
    case 6, 7 -> "weekend";
    default -> "error";
};
System.out.println(name);
  • Multiple values can be tied to one line like case 1, 2, 3 ->
  • If the value requires multiple lines, block + yield:
    String s = switch (n) {
        case 1 -> "one";
        case 2 -> {
            System.out.println("two!");
            yield "two";
        }
        default -> "?";
    };
    

3) 4 types of loops

for (int i = 0; i < 3; i++) { ... }
int j = 0; while (j < 3) { j++; }
int k = 0; do { k++; } while (k < 3);
int[] nums = {1, 2, 3};
for (int n : nums) { System.out.println(n); }   // enhanced for

4) break / continue

for (int i = 0; i < 10; i++) {
    if (i == 3) continue;   //Skip this episode
    if (i == 6) break;      //End of repeat
    System.out.print(i + " ");   // 0 1 2 4 5
}

See as example

Example 1 — IfElseDemo.java: Branch Basics

public class IfElseDemo {
    public static void main(String[] args) {
        int score = 72;
        String 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);
    }
}

Execution result

Score 72 -> C

Note: A one-line if body can omit the curly braces, but the official convention is to use curly braces.

Example 2 — SwitchExpression.java : -> / yield

public class SwitchExpression {
    public static void main(String[] args) {
        int day = 3;
        String kind = switch (day) {
            case 1, 2, 3, 4, 5 -> "weekdays";
            case 6, 7 -> "weekend";
            default -> "error";
        };
        System.out.println(day + "Days:" + kind);

        int n = 2;
        String word = switch (n) {
            case 1 -> "one";
            case 2 -> {
                System.out.println("two!");
                yield "two";
            }
            default -> "?";
        };
        System.out.println(word);
    }
}

Execution result

3 days: weekdays
two!
two

Memo: Switch expression must have a value determined (default is required).

Example 3 — Loops.java : for / while / enhanced for

public class Loops {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) sum += i;
        System.out.println("1+...+5 = " + sum);

        int j = 0;
        while (j < 3) {
            System.out.print(j + " ");
            j++;
        }
        System.out.println();

        int[] nums = {10, 20, 30};
        for (int n : nums) System.out.print(n + " ");
        System.out.println();
    }
}

Execution result

1+...+5 = 15
0 1 2 
10 20 30 

Note: enhanced for is safest when no index is needed.

Example 4 — BreakContinue.java: break/continue

public class BreakContinue {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 3) continue;
            if (i == 6) break;
            System.out.print(i + " ");
        }
        System.out.println();

        outer:
        for (int i = 0; i < 3; i++) {
            for (int k = 0; k < 3; k++) {
                if (i + k == 3) break outer;
                System.out.print("(" + i + "," + k + ") ");
            }
        }
        System.out.println();
    }
}

Execution result

0 1 2 4 5 
(0,0) (0,1) (0,2) (1,0) (1,1) 

Note: Label break is useful for escaping deep nests, but overuse can harm readability.

Common Mistakes

  1. Like if (a = 1), use = instead of == → Compilation error (int in place of boolean)
  2. Off-by-one (< vs <=) by incorrectly setting the repeat variable range.
  3. Forget break fall-through of classic switch
  4. Trying to modify collection elements in enhanced for ConcurrentModificationException
  5. default missing in switch expression

Cleanup

  • if or switch expression for branch
  • Repeat for for / while / enhanced for
  • break/continue and label jumping are sometimes useful

Try it yourself

cd 01_Basics/04_Control-statements/src
javac SwitchExpression.java
java SwitchExpression

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/BreakContinue.javaJava
public class BreakContinue {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 3) continue;
            if (i == 6) break;
            System.out.print(i + " ");
        }
        System.out.println();

        outer:
        for (int i = 0; i < 3; i++) {
            for (int k = 0; k < 3; k++) {
                if (i + k == 3) break outer;
                System.out.print("(" + i + "," + k + ") ");
            }
        }
        System.out.println();
    }
}
src/IfElseDemo.javaJava
public class IfElseDemo {
    public static void main(String[] args) {
        int score = 72;
        String 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);
    }
}
src/Loops.javaJava
public class Loops {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) sum += i;
        System.out.println("1+...+5 = " + sum);

        int j = 0;
        while (j < 3) {
            System.out.print(j + " ");
            j++;
        }
        System.out.println();

        int[] nums = {10, 20, 30};
        for (int n : nums) System.out.print(n + " ");
        System.out.println();
    }
}
src/SwitchExpression.javaJava
public class SwitchExpression {
    public static void main(String[] args) {
        int day = 3;
        String kind = switch (day) {
            case 1, 2, 3, 4, 5 -> "weekdays";
            case 6, 7 -> "weekend";
            default -> "error";
        };
        System.out.println(day + "Days:" + kind);

        int n = 2;
        String word = switch (n) {
            case 1 -> "one";
            case 2 -> {
                System.out.println("two!");
                yield "two";
            }
            default -> "?";
        };
        System.out.println(word);
    }
}

Assignment

Problem 1 — FizzBuzz

  • File name: Homework01.java
  • Core concepts: for, if/else if

Requirements

  • Prints from 1 to 15.
  • Fizz in multiples of 3, Buzz in multiples of 5, FizzBuzz in multiples of 15, and the rest remain as numbers.

Expected output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Hint

  • Check the multiples of 15 first.

Problem 2 — Menu Selection

  • File name: Homework02.java
  • Key concept: switch expression

Requirements

  • When the integer is menu = 2, the following is returned as a switch expression.
  • 1 → “New Menu”, 2 → “Recommended”, 3, 4 → “Best Seller”, Other → “None”
  • Output the results in Select: Featured format.

Expected output

Select: Featured

Problem 3 — Multiplication tables 2 to 5

  • File name: Homework03.java
  • Core concept: nested for

Requirements

  • Prints the multiplication table from column 2 to column 5.
  • The format is like 2 * 1 = 2.
  • One blank line between each column.

Expected output

2 * 1 = 2
2 * 2 = 4
...(omitted)

Hint

  • The outer for is a single number, but the inner for is a multiplication number.

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

Homework01.javaJava
/** FizzBuzz from 1 to 15.*/
public class Homework01 {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            if (i % 15 == 0) System.out.println("FizzBuzz");
            else if (i % 3 == 0) System.out.println("Fizz");
            else if (i % 5 == 0) System.out.println("Buzz");
            else System.out.println(i);
        }
    }
}
Homework02.javaJava
/** Menu decision with switch expression.*/
public class Homework02 {
    public static void main(String[] args) {
        int menu = 2;
        String label = switch (menu) {
            case 1 -> "New menu";
            case 2 -> "recommended";
            case 3, 4 -> "bestseller";
            default -> "None";
        };
        System.out.println("Select:" + label);
    }
}
Homework03.javaJava
/** Multiplication tables 2 to 5.*/
public class Homework03 {
    public static void main(String[] args) {
        for (int dan = 2; dan <= 5; dan++) {
            for (int i = 1; i <= 9; i++) {
                System.out.println(dan + " * " + i + " = " + (dan * i));
            }
            System.out.println();
        }
    }
}

Learn this lesson with a mentor

Work through the Java + Spring Boot track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now