While Loop in Java
The while loop in Java is a control flow statement that is used to execute a block of code repeatedly as long as a specified condition is true. It is useful when the number of iterations is not known before the execution of the program.
The Java while loop checks the condition before executing the loop body. If the condition is true, the code inside the loop executes; otherwise, the loop stops.
What is While Loop in Java?
A while loop in Java is an iteration statement that repeatedly executes a set of statements until the given condition becomes false.
It is called an entry-controlled loop because the condition is checked before executing the statements inside the loop.
Syntax of While Loop in Java
while (condition) {
// code to execute
}
Components of While Loop
Condition
Defines the condition that controls the execution of the loop.
Loop Body
Contains statements that execute repeatedly while the condition is true.
Update
Changes the loop variable to avoid infinite execution.
How While Loop Works in Java?
- The condition is checked first.
- If the condition is true, the loop body executes.
- After execution, the loop variable is updated.
- The condition is checked again.
- The loop stops when the condition becomes false.
Example of While Loop in Java
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5){
System.out.println(i);
i++;
}
}
}
2
3
4
5
While Loop Example: Print Even Numbers
public class Main {
public static void main(String[] args) {
int i = 2;
while(i <= 10) {
System.out.println(i);
i = i + 2;
}
}
}
4
6
8
10
Infinite While Loop in Java
An infinite while loop is a loop that never ends because its condition always remains true. It usually happens when the loop variable is not updated properly.
while (true) {
System.out.println("Hello Java");
}
Advantages of While Loop in Java
Flexible
Useful when the number of iterations is not fixed.
Simple Logic
Provides a simple way to repeat statements.
Condition Based
Runs until a specific condition becomes false.
Difference Between For Loop and While Loop
- For Loop: Used when the number of iterations is known.
- While Loop: Used when the number of iterations depends on a condition.
- For loop keeps initialization, condition, and update together.
- While loop contains only a condition in its syntax.