while Loop
In Java, the while
loop is used to repeatedly execute a block of code as long as a given boolean expression evaluates to true
. The loop continues iterating as long as the condition remains true. The basic syntax of the while
loop is as follows:
while (condition) {
// Code to be executed as long as the condition is true
}
Example:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
In this example:
int i = 1;
initializes a loop control variablei
to 1.while (i <= 5)
is the loop condition. As long as this condition istrue
, the loop continues.System.out.println(i);
prints the value ofi
.i++;
increments the value ofi
after each iteration.
The output of this program will be:
1
2
3
4
5
Infinite while Loop:
Be cautious when using a while
loop to avoid an infinite loop (a loop that never terminates). If the loop condition always evaluates to true
, the loop will continue indefinitely. For example:
// Caution: Infinite loop
while (true) {
// Code inside the loop
}
In the above example, the loop will never exit because the condition is always true
. It's important to ensure that the loop condition will eventually become false
to prevent infinite loops.
Do-While Loop:
The do-while
loop is similar to the while
loop, but it guarantees that the block of code is executed at least once, even if the loop condition is initially false
. The syntax is as follows:
do {
// Code to be executed
} while (condition);
Example:
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
In this example, the loop will execute at least once, printing numbers from 1 to 5.
The choice between while
and do-while
depends on whether you want the block of code to be executed at least once, regardless of the initial condition.