Java while loop statement
Overview
Java while loop can be used when the number of iterations is not known. The while loop executes as long as the loop condition is true. This loop checks the loop condition before executing the loop statements. (pre-check loop control)
while Loop Syntax
while ( boolean loop condition ) {
// loop statements
}
Examples
public static void main(String[] args) { int i=0; while(i < 5) { System.out.println(i); i++; } }
Infinite Loop
When the loop condition is always true the while loop executes forever until it’s interrupted by external signals. It may seem that infinite loops are undesirable when the program expects a fixed number of iterations. But in some cases infinite while loops are desirable. We can design an infinite while loop for an application server that runs forever to service its clients.
For example,
while(true)
while(1 == 1)
public class WhileLoopDemo { public static void main(String[] args) { while(true) { System.out.println("Infinite Loop"); } } }
A loop that doesn’t run
Interesting thing is that while loop might not ever run in some cases. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
This loop statement will not execute because i hold a value of 7 which is < 10. The loop condition ( i > 10 ) is false.
int i = 7;
while(i > 10) {
System.out.println(“This loop statement will not run”);
}
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :