Loop statements
For Loop
The for loop in Java is used to execute a block of code repeatedly for a fixed number of times. It is commonly used when the number of iterations is known in advance.
In a for loop, initialization, condition checking, and increment/decrement are written in a single line, which makes the code clean and easy to read.
Example
public class Main {
Β Β public static void main(String[] args) {
Β Β Β Β for (int i = 1; i <= 5; i++) {
Β Β Β Β Β Β System.out.println(i);
Β Β Β Β }
Β Β }
}
for-each loop
The for-each loop in Java is an enhanced version of the for loop used to iterate through arrays and collections in a simple way. It allows accessing each element one by one without using an index or manually controlling the loop counter.
The loop automatically moves from the first element to the last element, making the code easier to write and read.
Β
Example
public class Main {
Β Β public static void main(String[] args) {
Β Β Β Β int numbers[] = {10, 20, 30, 40, 50};
Β Β Β Β for (int num : numbers) {
Β Β Β Β Β Β System.out.println(num);
Β Β Β Β }
Β Β }
}
While Loop
A while loop in Java is an entry-controlled loop in which the condition is checked before executing the loop body. If the condition is true, the loop runs; if it is false, the loop stops. It is used to repeat a block of code as long as the given condition remains true.
Example
int i = 1;
while (i <= 5) {
Β Β System.out.println(i);
Β Β i++;
}
do-while loop
A do-while loop in Java is a type of loop that runs the code at least one time, because the condition is checked after executing the loop. After that, it keeps repeating the loop as long as the condition is true.
Example
int i = 1;
do {
Β Β System.out.println(i);
Β Β i++;
} while (i <= 5);