A while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
The while loop checks the condition before each iteration and only executes the loop body if the condition is true.
Syntax
The syntax for the while loop in Java is as follows:
while (condition) {
// Code to be executed
}
Where condition is a boolean expression that must return either true or false.
If the condition returns true, the loop body is executed, and if it returns false, the loop ends and the program control moves to the next statement following the loop.
Flow of Execution
- The condition is evaluated.
- If the condition is true, the loop body is executed, and the process goes back to step 1.
- If the condition is false, the loop ends and the program control moves to the next statement after the loop.
Example
Here is a simple example that demonstrates the use of a while loop in Java:
int i = 1;
while (i & lt; = 10) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
6
7
8
9
10
Infinite Loop
A while loop can also be used to create an infinite loop, which runs indefinitely until it is manually stopped or the program is terminated.
This can happen if the condition always returns true.
Here’s an example of an infinite loop:
while (true) {
System.out.println("Infinite loop");
}
Breaking the Loop
To break out of a while loop, you can use the break statement.
This statement immediately terminates the loop and moves the program control to the next statement after the loop.
Here’s an example:
int i = 1;
while (i & lt; = 10) {
if (i == 5) {
break;
}
System.out.println(i);
i++;
}
Output:
1
2
3
4
Skipping an Iteration
To skip the current iteration and move on to the next iteration, you can use the continue statement.
This statement immediately terminates the current iteration and moves the program control to the next iteration.
Here’s an example:
int i = 1;
while (i & lt; = 10) {
if (i % 2 == 0) {
i++;
continue;
}
System.out.println(i);
i++;
}
Output:
1
3
5
7
9
Conclusion
The while loop in Java is a powerful control flow statement that allows you to repeat a set of statements as long as a certain condition is true.
It is essential to make sure that the condition will eventually become false, otherwise the loop will run indefinitely, creating an infinite loop.
The break and continue statements can be used to modify the flow of the loop, making it a versatile tool for solving different problems.