In Java, loops are control flow statements used to repeat a block of code multiple times, based on a condition. Java supports several types of loops:
1. For Loop:
Used when the number of iterations is known beforehand.
java
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
2. While Loop:
Executes the code block as long as the condition is true. The condition is checked before each iteration.
java
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
3. Do-While Loop:
Similar to the while loop but checks the condition after executing the code block, ensuring the code runs at least once.
java
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
Break and Continue:
– break: Exits the loop immediately.
– continue: Skips the current iteration and moves to the next one.
Loops are essential for automating repetitive tasks in Java programs.