Introduction
The while
loop is one of the fundamental control flow statements in Java that allows repetitive execution of a block of code as long as a specified condition remains true. It is useful for situations where the number of iterations is not known beforehand and the loop needs to continue until a certain condition is met. In this chapter, we will explore the syntax, usage, and examples of the while
loop in Java.
Syntax
The basic syntax of the while
loop is as follows:
while (condition) {
// code to be executed
}
Key Points:
- The
condition
is evaluated before each iteration. - If the
condition
is true, the code inside thewhile
loop is executed. - If the
condition
is false, the loop terminates, and control passes to the next statement after the loop.
Example
Let’s consider an example where we use the while
loop to print numbers from 1 to 5.
Example Code:
public class WhileExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Infinite Loop
A while
loop can become an infinite loop if the condition never becomes false. This can happen if the loop control variable is not updated correctly.
Example of Infinite Loop:
public class InfiniteLoopExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
// Missing count++;
}
}
}
In this example, the count
variable is never incremented, so the condition count <= 5
remains true indefinitely, causing an infinite loop.
Using break in while Loop
The break
statement can be used to exit the loop prematurely, regardless of the condition.
Example with break:
public class BreakInWhileExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
if (count == 3) {
break;
}
System.out.println("Count: " + count);
count++;
}
}
}
Output:
Count: 1
Count: 2
Using continue in while Loop
The continue
statement skips the current iteration of the loop and proceeds with the next iteration.
Example with continue:
public class ContinueInWhileExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
if (count == 3) {
count++;
continue;
}
System.out.println("Count: " + count);
count++;
}
}
}
Output:
Count: 1
Count: 2
Count: 4
Count: 5
Diagram: Flow Chart of while Loop
Start
|
[initialize]
|
[condition]
|
/ \
True False
/ \
[execute] End
|
[update]
|
[condition]
|
True/False (loop continues)
Conclusion
The while
loop is a powerful control flow statement in Java that enables repetitive execution of a block of code based on a condition. It is particularly useful when the number of iterations is not known in advance and needs to be controlled by a condition. By understanding the syntax and usage of the while
loop, including how to manage infinite loops and use break
and continue
statements, you can write more flexible and efficient Java programs.