Module 2: Java Fundamentals
Loops in Java
Repeat work with for, while, and do-while loops.
Loops repeat code while a condition or iteration rule allows it. Java provides for, enhanced for, while, and do-while loops.
The for loop#
Use a for loop when the iteration setup and update are naturally expressed together.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
The loop initializes i to 1, checks i <= 5, executes the body, then increments i. It stops when the condition becomes false.
The while loop#
A while loop checks its condition before each iteration.
int count = 3;
while (count > 0) {
System.out.println(count);
count--;
}
Make sure that something in the loop can eventually make the condition false. Otherwise, the loop may never terminate.
The do-while loop#
A do-while loop runs its body at least once because its condition is checked at the end.
int attempt = 0;
do {
attempt++;
} while (attempt < 1);
Enhanced for loop#
Use the enhanced for loop to visit each element in an array or collection:
String[] languages = {"Java", "Python", "JavaScript"};
for (String language : languages) {
System.out.println(language);
}
break and continue#
break exits the nearest loop. continue skips the rest of the current iteration and moves to the next one. Use them when they make the logic clearer, not as a replacement for a well-structured condition.
Practice#
Print the numbers from 1 to 20. Then print only even numbers in that range. Finally, calculate the sum of the numbers from 1 to 100.