while Loops
Learn how to iterate with a while loop.
We'll cover the following...
Iteration changes the flow of control by repeating a set of statements, zero or more times until a condition is met.
Introduction
In loops, the boolean expression is evaluated before each iteration, including the first iteration. When the expression evaluates to true, the loop body is executed. This continues until the expression evaluates to false, after which the iteration ceases.
Java while loop
The while loop runs a set of instructions as long as a specified condition is true.
Here is it its syntax:
while (condition)
{
statement(s) // statements to be executed
}
Example
For example, we want to print all numbers up to on the screen. Run the program below to see how it’s done.
Press + to interact
Java
class whileLoop{public static void main(String args[]){int x = 0;// While loopwhile (x <= 5) // Condition{System.out.println(x); // Printing x if <= 5x ++; // Incrementing x in every iteration}System.out.println ("Hi");}}
At line 5, we declare an x variable (type int), and initialize it with ...
Ask