In Java, loops are control flow statements that allow you to execute a block of code repeatedly. There are three types of loops: for loop, while loop, and do-while loop.
- For loop: A for loop is used when you know how many times you want to execute a block of code. The basic syntax of a for loop is as follows:
for (initialization; condition; increment) {
// code to execute repeatedly
}
Here, initialization
is an expression that initializes a variable used in the loop, condition
is an expression that is evaluated before each iteration of the loop, and increment
is an expression that is executed after each iteration of the loop. The loop will continue to execute the block of code within the curly braces as long as the condition
is true.
For example, consider the following code that uses a for loop to print the numbers from 1 to 5:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
In this case, the initialization
statement initializes the variable i
to 1, the condition
statement specifies that the loop should continue as long as i
is less than or equal to 5, and the increment
statement increments i
by 1 after each iteration of the loop.
- While loop: A while loop is used when you don’t know how many times you want to execute a block of code, but you know the condition under which the loop should continue. The basic syntax of a while loop is as follows:
while (condition) {
// code to execute repeatedly
}
Here, condition
is an expression that is evaluated before each iteration of the loop. The loop will continue to execute the block of code within the curly braces as long as the condition
is true.
For example, consider the following code that uses a while loop to print the numbers from 1 to 5:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
In this case, the condition
is the expression i <= 5
. The loop will continue to execute the block of code within the curly braces as long as i
is less than or equal to 5.
- Do-while loop: A do-while loop is similar to a while loop, but the block of code within the loop is executed at least once, even if the
condition
is false. The basic syntax of a do-while loop is as follows:
do {
// code to execute repeatedly
} while (condition);
Here, the block of code within the curly braces is executed first, and then the condition
is evaluated. If the condition
is true, the loop will continue to execute the block of code within the curly braces.
For example, consider the following code that uses a do-while loop to print the numbers from 1 to 5:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
In this case, the block of code within the curly braces is executed first, and then the condition
is evaluated. Since i
is less than or equal to 5, the loop will continue to execute the block of code.