Loops
Repeat code efficiently! Master For, While, and Do-While loops in Java.
Repeat code efficiently! Master For, While, and Do-While loops in Java. This hands-on tutorial focuses on practical implementation of loops concepts.
Loops
Loops can execute a block of code as long as a specified condition is reached. They save time, reduce errors, and make code more readable.
1. while Loop
Loops through a block of code types as long as a specified condition is logical true.
while (condition) {
// code block to be executed
}
2. do...while Loop
The do...while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do {
// code block to be executed
}
while (condition);
3. for Loop
When you know exactly how many times you want to loop through a block of code, use the for loop.
// for (statement 1; statement 2; statement 3)
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
- Statement 1: Executed one time before the loop starts (Variable initialization).
- Statement 2: Defines the condition for running the loop.
- Statement 3: Executed every time after the code block has been executed (Increment/Decrement).
4. for-each Loop
Exclusively to loop through elements in an array or other collections.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Break and Continue
break: Jumps out of a loop.continue: Breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
Interactive Code
Try the standard loop vs the enhanced for-each loop!
AI Mentor
Confused about "Java loops: while, do-while, for, break and continue"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3Which loop always executes at least once?
Next Steps
Enough small snippets. In the next module, we will learn how to organize code into reusable Methods.