While Loop in Java | Control Flow in Java
The while loop in Java is a control flow statement that allows code to be executed repeatedly based on a boolean condition. It's useful for scenarios where the number of iterations is not known beforehand.
Key Points on While Loop:
- The while loop checks the condition before each iteration.
- It’s suitable when the number of iterations is uncertain.
- Make sure to modify the loop variable within the loop to avoid infinite loops.
- The loop will execute zero or more times based on the condition.
- It can be combined with control statements like break and continue.
Syntax of While Loop:
Syntax Example
while (condition) {
// Code to execute in each iteration
}
Example of While Loop in Java:
This example demonstrates a basic while loop that prints numbers from 1 to 5.
Code Example 1
public class PrintNumbersWhile {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++; // Increment the loop variable
}
}
}
Output for Code Example 1:
1
2
3
4
5
2
3
4
5
Using Control Statements:
This example shows how to use the break statement in a while loop.
Code Example 2
public class BreakWhileExample {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
i++;
}
}
}
Output for Code Example 2:
1
2
3
4
2
3
4
Example of a While Loop with Condition Change:
This example uses a while loop to sum numbers until a certain limit is reached.
Code Example 3
public class SumWhileExample {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i <= 5) {
sum += i; // Add i to sum
i++; // Increment i
}
System.out.println("Sum: " + sum);
}
}
Output for Code Example 3:
Sum: 15
Detailed Explanation:
- Condition: The loop continues as long as this condition is true. If false, the loop exits.
- Increment/Decrement: Ensure that the loop variable is modified within the loop to avoid infinite loops.
- Control Statements: Use break to exit the loop early and continue to skip to the next iteration.
By mastering the while loop, developers can effectively manage the flow of their Java programs, especially in situations where the number of iterations is not predetermined.