AppDividend
Latest Code Tutorials

Java While Loop Example | While Loop In Java

0

Java While Loop Example | While Loop In Java is today’s topic. Loops can execute the block of code as long as the specified condition is reached. The while loop loops through the block of code as long as the specified condition is true.  A Java while loop is used to iterate the part of a program several times. If a number of iteration is not fixed, then it is recommended to use the while loop. If a number of iterations are fixed then use the for loop.

Java While Loop

The while statement evaluates an expression, which must return the boolean value. If the expression evaluates to a true boolean value, a while statement executes a statement(s) in a while block. A 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 a 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 run. When 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. I have recently written the for loop example. 

Finally, While loop example is over.

Leave A Reply

Your email address will not be published.

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