AppDividend
Latest Code Tutorials

Java while loop: The Complete Guide

Java loops can execute the code block as long as the specified condition is reached. The while loop loops through the code block as long as the specified condition is true. A Java while loop is used to iterate the part of a program several times.

If several iterations are not fixed, it is recommended to use the while loop. If several iterations are fixed, then use the for loop.

Java while loop

Java while loop evaluates an expression, which must return the boolean value. If the expression evaluates to a true boolean value, the while statement executes a statement(s) in a while block. The while statement continues testing the expression and executing its block until that expression evaluates to false

How while loop works

The test expression inside parenthesis is a boolean expression.

If the test expression is evaluated to true,

  1. The statements inside a while loop are executed.
  2. Then, test expression is evaluated again.

The above process goes on until the test expression is evaluated to false.

If a test expression is evaluated to false,

  1. The While loop is terminated.

See the following syntax of While loop.

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

See the following code example.

class Loop {
  public static void main(String args[]) {
    int i = 1;  
    while (i <= 6) {
      System.out.println(i);
      i++;
    }
  }
}

See the following output.

➜  java javac Loop.java
➜  java java Loop
1
2
3
4
5
6
➜  java

Here, a key point of a while loop is that the loop might not ever rTherefore, whenWhen an expression is tested, and the result is false, that loop body will be skipped, and the first statement after that while loop will be executed.

Here, one more thing you need to keep in mind that do not forget to increase a variable used in the condition, otherwise that loop will never end.

Java Infinitive While Loop

If you pass true in the while loop, it will be infinite while loop.

See the following syntax.

while(true){  
  //code to be executed  
}

See the following code example.

class Loop {
  public static void main(String args[]) {
    while (true) {
      System.out.println("infinite while loop");
    }
  }
}

It will print Infinite while loop.

That’s it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.