Introduction to Java: While Loop

Posted by Hayri Cicek on June 11, 2019


While-loop executes a block of code as long as a specified condition is true.

Example


public class WhileLoop {
    public static void main(String[] args) {
        int i = 0;
        while (i < 10) {
            System.out.println("number: " + i);
            i++;
        }
    }
}


If you forget to increase the variable in the condition, then you will end up with infinite loop, which will never end.

Output:

$ javac WhileLoop.java
$ java WhileLoop

number: 0
number: 1
number: 2
number: 3
number: 4
number: 5
number: 6
number: 7
number: 8
number: 9


Do/While Loop
The Do/While loop is similar to the while loop except that the condition is checked after the statements are executed and will always execute at least once.

Example:


public class DoWhile {
    public static void main(String[] args) {
        int i = 0;

        do {
            System.out.println("number " + i);
            i++;
        } while (i <= 10);
    }
}


Output:

$ javac DoWhile.java
$ java DoWhile

number 0
number 1
number 2
number 3
number 4
number 5
number 6
number 7
number 8
number 9
number 10


Share this: