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
- Print 1 to 20 with a for loop.
- Create a grade classifier.
- Use switch for a simple day-number menu.
Key Takeaways
- Branching handles decisions.
- Loops handle repetition.
- Keep loop boundaries explicit and test edge cases.
Previous
← Variables, Types and Operators
← Variables, Types and Operators
Next
Methods and Arrays →
Methods and Arrays →