Java Tutorial

Conditions and Loops

Control program flow with if, switch, for, while and enhanced for loops.

Concept

Use if/else when branching depends on boolean expressions. switch is useful when one value is matched against multiple discrete cases.

for loops are common when the number of iterations is known; while loops fit condition-driven repetition. The enhanced for loop is concise for arrays and collections.

Example

int score = 72;
if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Practice more");
}
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.

Practice Tasks

  1. Print 1 to 20 with a for loop.
  2. Create a grade classifier.
  3. Use switch for a simple day-number menu.

Key Takeaways

  • Branching handles decisions.
  • Loops handle repetition.
  • Keep loop boundaries explicit and test edge cases.