Java while loop Examples



This Java example demonstrates how to use while loop in Java with examples. 

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.

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

The while Loop with No Body Example

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

Infinite while Loop Example

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