while loop in Java with examples

In Java, a "while" loop is a control flow statement that lets you run a block of code over and over again as long as a certain condition holds true.

Java while loop syntax

The general form for using a "while" loop in Java is as follows:

while (condition) {
   // code to continue its execution
   // until the given "condition" is true.
}

In this case, "condition" is the expression that is evaluated before each loop iteration. If condition is true, the code inside the block is executed. This process is repeated until the condition is met, at which point the loop ends and program control returns to the statement following the "while" loop. As an example:

Java Code
public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}
Output
1
2
3
4
5

The program sets the variable "i" to 1. With the condition "i <= 5," the program enters a "while" loop. This means that the loop will keep running as long as "i" is less than or equal to 5.

The program prints the value of "i" within the loop using the "System.out.println()" method. The program increases "i" by one using the "i++" statement.

The program checks the loop condition "i <= 5" after each iteration of the loop. If the condition is true, the loop continues to execute; otherwise, the loop terminates.

Java while loop example

I already mentioned one example right above this section. But I'm willing to include a few more examples demonstrating the "while" loop in Java.

Java Code
import java.util.Scanner;

public class WhileLoopExample {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        int count = 0;
        System.out.print("How many even numbers do you want to print? ");
        int n = input.nextInt();
        
        System.out.println("\nList of first " + n + " even numbers:");
        int i = 0;
        while (count < n) {
            if (i % 2 == 0) {
                System.out.print(i + " ");
                count++;
            }
            i++;
        }
    }
}
Output
How many even numbers do you want to print? 6

List of first 6 even numbers:
0 2 4 6 8 10

When we run the Java program you provided, it will ask the user for a number n and then print the first n even numbers in the same way as shown in the above output.

0 is regarded as an even number. An even number is any integer that is divisible by two, and 0 is an even number because 0 divided by two equals 0 with no remainder. As a result, in mathematics, 0 is classified as an even number.

Following is the step-by-step explanation of the above Java program demonstrating the "while" loop.

Here is another example that finds and prints the factorial of a given number using the "while" loop.

Java Code
import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int num = input.nextInt();

        int factorial = 1;
        int i = 1;

        while (i <= num) {
            factorial *= i;
            i++;
        }

        System.out.println("The factorial of " + num + " is " + factorial + ".");
    }
}
Output
Enter a positive integer: 6
The factorial of 6 is 720.

Before we wrap up our discussion of the "while" loop, here's a program that counts down from 10, printing exactly 10 lines of "tick":

public class JavaProgram {
    public static void main(String args[]) {
        int n = 10;

        while(n > 0) {
            System.out.println("tick " + n);
            n--;
        }
    }
}

When the above Java program is compiled and executed, it will produce the following output:

java while loop

Java Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!