Java While Loop Explaination
This chapter will examine the Java while loop with examples, hoping that it will help us in our learning process.
In Java, a while loop is a control flow instruction that repeatedly executes code when a given Boolean condition is met. As a repeating if statement, a while loop can be viewed as a conditional statement.
While loops are described as repeating if statements. The while loop should be implemented if the number of iterations is not fixed.
Java while loop can utilized when a block of statements needs to be executed repeatedly.
Loops
As long as a specified condition is met, a loop can execute a block of code.
It is convenient to use loops because they save time, reduce errors, and improve the readability of code.
Java While Loop
A while loop iterates through a block of code until a condition is met:
Syntax:
while (condition) { // Executable block of code }
Following is an example of a loop that runs as long as the variable (mrx) is less than 7:
Example: 
Example: 
Remember : It is important to increase the variable used in the condition otherwise the loop will never end!
What does a While loop do?
-
The control is taken over by the while loop.
- Condition is reached in the flow
-
The condition is tested.
-
The flow enters the body if Condition is true.
-
The flow exits the loop if Condition yields false
-
-
The loop’s body executes the statements inside it.
-
An update is performed.
-
The control flows back to Step 2.
-
Flow has exited the while loop.
The Do/While Loop
There is a variant of the while loop called the do/while loop. Once the code block is executed, it will check if the condition is true, and then repeat the loop if it is.
Syntax:
do { // Execution of code block } while (condition);
Below is an example of a do/while loop. Even if the condition is false, the loop will still be executed at least once, since the code block is executed before the condition is tested.
Example: 
We can also use the do-while loop to print starting 10 numbers in a reverse order:
Example: 
Important : Remember to increase the variable used in the condition, otherwise the loop will never end!