Java While Loop


Loops

Loops can block a code block as long as the specified condition is reached.

Loops work because they save time, reduce errors, and make the code more readable.


Java While Loop

the while loop entering the code block as long as the condition stated is true:


Syntax
while (condition) {
              // code block to be executed
            }
            

In the example below, the code in the loop will apply, repeatedly, as long as the variable (i) is less than 5:


Example
int i = 0;
            while (i < 5) {
              System.out.println(i);
              i++;
            }
            

Note: Do not forget to increase the flexibility used in the case, otherwise the loop will not expire!


the Do/While Loop

Thedo / while loop is a type of while loop at a time. This loop will use a code block and, before checking that status is true, will reopen the loop as long as the status is true.


Syntax
do {
              // code block to be executed
            }
            while (condition);
            

The example below uses a do/while loop. The loop will always be used at least once, even if the condition is false, because the code cache is used before the status check:


Example
int i = 0;
do
{ System.out.println(i); i++; } while (i < 5);

Do not forget to increase the flexibility used in the case, otherwise the loop will not expire!