Java Foundations

Lesson 3 of 7

Control Flow and Loops

Java's control flow will look familiar if you know C-family syntax, curly braces mark blocks, conditions need parentheses.

int xp = 45;

if (xp >= 100) {
    System.out.println("Level up!");
} else if (xp >= 50) {
    System.out.println("Almost there");
} else {
    System.out.println("Keep going");
}

Loops

for (int i = 0; i < 5; i++) {
    System.out.println("Iteration " + i);
}

int[] scores = {90, 85, 77};
for (int score : scores) {   // "enhanced for", like Python's for-in
    System.out.println(score);
}

int tries = 0;
while (tries < 3) {
    tries++;
}

The enhanced for (int score : scores) form reads as "for each score in scores", it's the idiomatic way to iterate when you don't need the index.

Switch expressions

Modern Java's switch can be used as an expression that directly produces a value, not just a statement that runs code:

String tier = switch (xp / 25) {
    case 0 -> "Bronze";
    case 1 -> "Silver";
    case 2 -> "Gold";
    default -> "Platinum";
};

Each case uses -> instead of :, which means no accidental "fallthrough" to the next case, a common bug in older-style switch statements, and the whole thing evaluates directly to tier.

📝 Control Flow Quiz

Passing score: 70%
  1. 1.What does "for (int score : scores)" mean?

  2. 2.A modern switch expression using -> can directly produce a value assigned to a variable.

  3. 3.The loop that keeps running as long as a condition stays true, checked before each iteration, is a ____ loop.