The while loop is a loop statement used to iterate over a sequence of code as long as a condition is true.
How Does the Java while Loop Work?
The general syntax of the while loop is as follows:
while(boolean condition) {
// write the code that you want to execute here
// so long as the boolean condition above
// resolves to TRUE
}
The boolean condition is checked before each iteration of the loop. When the boolean condition is false, the code block will be skipped, and the program will continue with the code after the while loop.
If the condition is false when your program arrives at the while loop for the first time, the code inside the loop will never be run.
Infinite while Loop
An infinite while loop is a loop that continues forever. However, there are times that you occasionally use such a loop (with an escape case). Generally, you should do everything possible to avoid infinite loops, as they will break your application. By setting the condition of the while loop to true, the loop will never exit. For example:
while(true){
// this code will execute forever
// unless it contains an escape case
}
while Loop in Java Example
The following code prints out numbers 1-10 using a while loop.
class Main {
public static void main(String[] args){
int x = 1;
while(x < 11){
System.out.println("x is : " + x);
x++;
}
}
}
The condition x < 11 is checked before every loop. When x gets incremented to 11, the condition evaluates to false, the execution exits the while loop, and the program finishes.
That's it! There isn't much to say about while loops, so that's all you need to know to use them.
Summary: What is the while Loop in Java?
- The
whileloop will continually execute its code until its condition isfalse - Infinite
whileloops should almost always be avoided - A
whileloop will only execute its code if the condition evaluates totrueat least once
Syntax
Here's the while loop syntax, where you can substitute the variables starting with your_ with your values.
while(your_condition_is_true) {
// your_code
}