The while loop in Java is used to repeatedly execute a block of code as long as a given condition remains true. It is best suited when the number of iterations is not known in advance.
// Basic syntax of while loop in Java
while(condition){
// statements
}
// Print numbers from 1 to 5 using while loop
class WhileDemo {
public static void main(String[] args) {
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}
}
}
1
2
3
4
5
The loop starts with i = 1. As long as i <= 5 is true, the loop runs and increments i by 1 each time.
Set a limit and watch the loop run step-by-step!
while when iterations are uncertain