Free degree-level programming lessons for careful independent study.

Degree Level Programmes · Programming 1 · Lesson 11

Selection and Iteration in Java

Build programs that choose between paths and repeat work using if, switch, while and for.

Lesson Overview

Build programs that choose between paths and repeat work using if, switch, while and for.

Portfolio focus: Write a menu with three choices.

ConceptControl flow
Run fileSelectionAndIterationDemo.java
BaselineWeek 1: start carefully Week 2: repeat, test, improve Week 3: repeat, test, improve
Evidence3 tasks

Starter: think before typing

Before running this control flow example, find the line where the main idea becomes active. Write a prediction: what must already be true for that line to work, and what should be different after it runs? The checked run ends with `Week 1: start carefully Week 2: repeat, test, improve Week 3: repeat, test, improve`; predict how the focus line helps produce that evidence.

Learning Objectives

  • Use if/else for decisions.
  • Use for loops when the repeat count is known.
  • Use while loops when repetition depends on a condition.
  • Trace loop variables to avoid off-by-one errors.

Learning Outcomes

  • By the end of the lesson, you can use if/else for decisions.
  • By the end of the lesson, you can use for loops when the repeat count is known.
  • By the end of the lesson, you can use while loops when repetition depends on a condition.
  • By the end of the lesson, you can trace loop variables to avoid off-by-one errors.

Why this idea exists

Sequence, selection and iteration are the core control structures behind structured programming, a movement that pushed programmers away from tangled jumps and towards readable blocks of logic.

Selection lets a program respond to state. Iteration lets it scale effort by repeating a reliable process. Together they turn a fixed list of instructions into a general solution for many inputs.

Degree-level work expects more than knowing the syntax. You should be able to justify why a `for` loop, `while` loop, `if` chain or `switch` fits the shape of the problem and how you know it terminates correctly.

Deep dive

Mechanism in this example

The important mechanism is visible around `for (int week = 1; week <= 3; week++) {`. Read it as a concrete move in the program, not as decorative syntax: identify what value, object, branch, call or boundary is being created at that point.

Design pressure

Degree-level work expects more than knowing the syntax. You should be able to justify why a `for` loop, `while` loop, `if` chain or `switch` fits the shape of the problem and how you know it terminates correctly.

Failure mode to watch

For Selection and Iteration in Java, deliberately disturb the assumption behind `for (int week = 1; week <= 3; week++) {`: use an awkward value, missing input, wrong order of calls or boundary case. The useful question is how that disturbance exposes a weakness in the control flow design.

Extension step

Extend the example by doing this: Loop until the user chooses quit. The point is to make one small change that forces you to revisit the concept, rather than adding unrelated features.

Portfolio standard

The portfolio note should not repeat the lesson wording. It should show the edited code, the run result, and your own explanation of this evidence: create a trace table for one loop.

Lesson visual

A photo-real desk scene with printed loop trace table, coloured arrows for if decisions and a laptop showing Java loop code.
A photo-real desk scene with printed loop trace table, coloured arrows for if decisions and a laptop showing Java loop code.Download visual

Type this and run it

Create SelectionAndIterationDemo.java, type the program, and run it before changing anything. This section is about reproducing the checked baseline.

public class SelectionAndIterationDemo {
  public static void main(String[] args) {
    for (int week = 1; week <= 3; week++) {
      if (week == 1) {
        System.out.println("Week " + week + ": start carefully");
      } else {
        System.out.println("Week " + week + ": repeat, test, improve");
      }
    }
  }
}

Build and run it with:

javac SelectionAndIterationDemo.java && java SelectionAndIterationDemo

Expected baseline: Week 1: start carefully Week 2: repeat, test, improve Week 3: repeat, test, improve

Run the code in your browser

Use the editor as an experiment surface. First run the checked version, then make one small change to the part of the program that demonstrates control flow and compare the new behaviour with the reference output.

Line-by-line explanation

Read the code as a sequence of responsibilities. The focus line for this lesson is for (int week = 1; week <= 3; week++) {; the surrounding lines prepare it, use its result or make the behaviour observable.

public class SelectionAndIterationDemo {

This names the runnable class for the Selection and Iteration in Java example, giving the compiler and JVM one clear unit to build.

public static void main(String[] args) {

This is the program entry point. In Selection and Iteration in Java, it keeps the demonstration of control flow in one traceable starting script.

for (int week = 1; week <= 3; week++) {

This introduces week as named state for Selection and Iteration in Java. Later lines can read, update, pass or print that specific value as evidence.

if (week == 1) {

This makes the Selection and Iteration in Java decision point. Trace the condition first, then trace only the branch that can actually run.

System.out.println("Week " + week + ": start carefully");

This prints "Week " + week + ": start carefully" as the observable evidence for Selection and Iteration in Java. The output lets the learner check whether the control flow idea behaved as predicted.

} else {

This opens the alternative Selection and Iteration in Java branch, which runs only when the earlier condition is false.

System.out.println("Week " + week + ": repeat, test, improve");

This prints "Week " + week + ": repeat, test, improve" as the observable evidence for Selection and Iteration in Java. The output lets the learner check whether the control flow idea behaved as predicted.

}

This closes the innermost Selection and Iteration in Java block, so the immediately preceding method, branch or loop has finished.

}

This closes the outer Selection and Iteration in Java structure, returning the reader to the surrounding class or file.

}

This closing brace number 3 completes another layer of the Selection and Iteration in Java source structure Java has been checking.

}

This closing brace number 4 completes another layer of the Selection and Iteration in Java source structure Java has been checking.

Worked example

From code to explanation

Problem: Use Selection and Iteration in Java to complete a small portfolio-quality step: Write a menu with three choices.

Method: Locate the line `for (int week = 1; week <= 3; week++) {`, explain the exact role it plays, then decide what you would change to extend the example without changing the whole program.

Reveal worked answer

The checked run should produce `Week 1: start carefully Week 2: repeat, test, improve Week 3: repeat, test, improve`. A strong answer links the result back to control flow: what was created, selected, stored, called or protected, and why that matters for the portfolio task.

Trace the program

Before: Before the key operation, identify the relevant value, object, branch or resource that the control flow concept depends on.

During: Trace `for (int week = 1; week <= 3; week++) {` as the Selection and Iteration in Java example executes. Say whether that operation creates data, checks a condition, calls behaviour, stores information or crosses a boundary.

After: Compare the run with the expected evidence: `Week 1: start carefully Week 2: repeat, test, improve Week 3: repeat, test, improve`.

Change: Now loop until the user chooses quit, run again, and explain the smallest reason the behaviour changed.

Common misconception

A common mistake in selection and iteration in java is treating the example as a finished answer. For control flow, the important question is narrower: which operation carries the idea, what does it make possible, and what would break if you changed it carelessly?

Quick checks

1. In this Selection and Iteration in Java example, what is the best reason to focus on `for (int week = 1; week <= 3; week++) {`?

2. Which evidence is strongest after you edit and rerun this example?

How to study this lesson

For Selection and Iteration in Java, predict how control flow changes the run before you press Run.

Use the first portfolio task as your main edit: Write a menu with three choices.

Use the second task as your variation: Loop until the user chooses quit.

Finish with evidence, not a diary entry: Create a trace table for one loop.

Portfolio Practice

  1. Write a menu with three choices.
  2. Loop until the user chooses quit.
  3. Create a trace table for one loop.

Final self-check

Can you explain the key operation?

Explain the line identified in the quick check in one or two sentences. Your answer should say what it does before the output Week 1: start carefully Week 2: repeat, test, improve Week 3: repeat, test, improve appears.

Can you justify the portfolio evidence?

Your evidence should include the original run, one edited run, and a short note explaining how the edit affected control flow.

Study route

Practise control flow by predicting the Java example, typing it, running it in the browser, tracing the result and saving portfolio evidence.

Next, move into If Statements, Determinism and Safer Control Flow and carry forward one improvement from this lesson into the next program.