while Loop in Java

In previous tutorial, we saw about for loop and enhanced for loop, and in this tutorial we will learn about while loop in java.

In java programming, while loop is used to execute a specific block of code repeated until a certain condition is matched. A while can be considered as repetition of if statements. While loop is used when the number of iterations are not fixed.

Syntax

while (condition) {
   //block of code to be executed.
}

In a while loop, we check the condition of the loop at the start. If the condition evaluated is true, then the block of code inside the loop’s body statements are executed. This is the reason why while loop is known as Entry Controlled Loop.

When the condition is evaluated to true, then the block of code inside the loop’s body statements are executed. Usually, the statements contain an update value for the variable being processed for the next iteration.

When the condition becomes false, the loop terminates which marks the end of its life cycle.

Example 1

You can find the code here

package com.qacaffe.examples.ControlStatements;

public class While {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            System.out.println(i);
            i++;
        }
    }
}

/*
output :
1
2
3
4
5
6
7
8
9
10
 */

Example 2

package com.qacaffe.examples.ControlStatements;

import java.util.Scanner;

public class While2 {

    public static void main(String[] args) {

        int payRatePerHour = 20;
        int maxHours = 40;
        double totalHoursWorked;
        String cont;

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your work hours");
        totalHoursWorked = scanner.nextDouble();

        //Logic to validate input
        while ((totalHoursWorked < 1) || (totalHoursWorked > maxHours)) {
            System.out.println("Invalid entry!!! Your hours must be between 1 and 40.Do you want to continue?");
            System.out.println("Press 'y' to continue and 'n' to quit.");
            cont = scanner.next();
            if (cont.equalsIgnoreCase("y")) {
                System.out.println("Enter number of hours you worked for this week.");
                totalHoursWorked = scanner.nextDouble();
            } else {
                if (cont.equalsIgnoreCase("n")) {
                    System.exit(0);
                    System.out.println("Thank you for using Employee salary calculation system.");
                }
            }
        }

        //Calculation of gross salary.
        double salary = payRatePerHour * totalHoursWorked;
        System.out.println("Your salary for this week is $" + salary);
    }
}

/*
Output:
Enter your work hours
40
Your salary for this week is $800.0
 */

Rutu Shah