← Java roadmap

Topic 3 of 30 · Beginner

Control Flow & Loops

if/else, switch expressions, for, while and enhanced for.

Concept

if / else if / else choose a branch. Modern switch expressions (Java 14+) use arrows, return a value and don't fall through.

for loops suit known counts, while loops repeat until a condition fails, do-while runs at least once, and the enhanced for iterates arrays and collections.

break exits a loop, continue skips to the next iteration; labelled breaks exit nested loops.

Code (Java 21)

int marks = 82;
String grade = marks >= 90 ? "A+" : marks >= 75 ? "A" : "B";

String day = "SAT";
int hours = switch (day) {
    case "SAT", "SUN" -> 0;
    case "FRI" -> 6;
    default -> 8;
};

int[] nums = {4, 7, 1};
for (int n : nums) {
    if (n == 7) continue;
    System.out.println(n);
}

Remember

  • Arrow switch has no fall-through.
  • Enhanced for can't modify the index.
  • Avoid deep nesting — return early.

Interview questions

while vs do-while?

while checks the condition first and may run zero times; do-while runs the body at least once.

Can switch work on strings?

Yes, since Java 7, along with ints, enums and (with pattern matching) other types in newer versions.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Control Flow & Loops” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.