Java while Loop with Examples


In this chapter, we will learn how to use while loop with examples. The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true.

Table of contents

  1. How while Loop Works?
  2. Simple while Loop Example
  3. The while Loop with No Body
  4. Infinite while Loop

Syntax

while(condition) {
// body of a loop
}
The condition can be any boolean expression. The body of the loop will be executed as long as the conditional expression is true. When the condition becomes false, control passes to the next line of code immediately following the loop. 
The curly braces are unnecessary if only a single statement is being repeated.

1. How while loop works?

In a while loop, a condition is evaluated first, and if it returns true then the statements inside while loop execute. When the condition returns false, the control comes out of a loop and jumps to the next statement after a while loop.


2. Simple while Loop Example

Here is a while loop that counts down from 10, printing exactly ten lines of "tick":
package net.javaguides.corejava.controlstatements.loops;

public class WhileLoopExample {
    public static void main(String args[]) {
        int n = 10;
        while (n > 0) {
            System.out.println("tick " + n);
            n--;
        }
    }
}
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1

3. The while Loop with No Body

The body of the while (or any other of Java’s loops) can be empty. This is because a null statement (one that consists only of a semicolon) is syntactically valid in Java. For example, consider the following program:
package net.javaguides.corejava.controlstatements.loops;

public class WhileLoopNoBody {
    public static void main(String args[]) {
        int i, j;
        i = 100;
        j = 200;
        // find midpoint between i and j
        while (++i < --j)
        ; // no body in this loop
        System.out.println("Midpoint is " + i);
    }
}
Output:
Midpoint is 150

4. Infinite while Loop

If you pass true in the while loop, it will be an infinite while loop.
Syntax:
while(true){  
//code to be executed  
} 
Example:
public class WhileExample {
    public static void main(String[] args) {
        while (true) {
            System.out.println("infinitive while loop");
        }
    }
}
Output:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
Now, you need to press ctrl+c to exit from the program.

Comments