Java While & Do-While Loop

While & Do-While Loop in Java

While Loop

In Java, a while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. It’s often used when you don’t know in advance how many times you need to execute the loop, but you want to keep executing as long as a condition remains true.

Structure of while loop

while (condition) // Checking condition
            {
            // Code to execute as long as the condition is true
            }

While Loop Statement

public class Main {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 3) {
            System.out.println(“Count: ” + count);
            count++;
        }
        System.out.println(“Loop has ended.”);
    }
}

Output:
Count: 1
Count: 2
Count: 3
Loop has ended.

Code Explanation

public class Main {

This defines a public class named Main. A class is a blueprint for creating objects, and public means that this class can be accessed from outside its containing package.

public static void main(String[] args) {

This is the entry point of your Java program. The main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program.

int count = 1;

This line declares an integer variable named count and initializes it with the value 1.

while (count <= 3) {

This is a while loop that will execute the code inside the curly braces {} as long as the condition count <= 3 is true.

Loop Execution:
1. The count variable value is 1, and the while loop checks if count is less than or equal to 3. Since the condition is true, the code inside the curly braces {} will execute, printing the count value and increasing it by 1 (count++).
2. The count variable value is 2, and the while loop checks if count is less than or equal to 3. Since the condition is true, the code inside the curly braces {} will execute, printing the count value and increasing it by 1 (count++).
3. The count variable value is 3, and the while loop checks if count is less than or equal to 3. Since the condition is true, the code inside the curly braces {} will execute, printing the count value and increasing it by 1 (count++).
4. The count variable value is 4, and the while loop checks if count is less than or equal to 3. Since the condition is false, the code inside the curly braces {} will not execute and the loop will stop
                                                      System.out.println(“Count: ” + count);
● This line prints the current value of count to the console, along with the text “Count: “.
              count++;
● This line increments the value of count by 1.
     }
     System.out.println(“Loop has ended.”);
● This line prints “Loop has ended.” to the console after the loop has finished executing.

Output:
Count: 1
Count: 2
Count: 3
Loop has ended.

Nested While Loop in Java

Structure of nested while loop

while (outer condition)
    {
        // Outer loop code
        while (inner condition)
        {
        // Inner loop code
    }
}

Scenario: Write a Java program using a nested while loop to generate and print a multiplication table for the number 2. The table should display the multiplication results from 2 × 1 to 2 × 5. Each row of the table should represent the multiplication of 2 with a different number from 1 to 5.

public class Main {
    public static void main(String[] args) {
        int i = 2;
        while (i <= 2) {
            int j = 1;
            while (j <= 5) {
                int result = i * j;
                System.out.print(result + “\t”);
                j++;
            }
            System.out.println();
            i++;
        }
    }
}

Output: 2   4   6   8   10

Code Explanation

public class Main

Defines a public class named Main. In Java, the class is the primary building block for creating an application, and public allows it to be accessible from outside its package.

public static void main(String[] args)

This is the entry point of the Java program. The main method is where program execution begins. It takes an array of String as a parameter (args), which can be used to pass command-line arguments.

int i = 2;

Declares an integer variable i and initializes it to 2. This variable represents the multiplier (2) for the multiplication table.

while (i <= 2)

The outer while loop checks if i is less than or equal to 2. Since i is initialized to 2, the loop executes once to print the multiplication table for 2.
        1. When i is 2, the condition i <= 2 is true, so the code inside the loop executes. The value of i increments after this
            iteration (i++), making i equal to 3.
        2. On the next check, i becomes 3, so the condition i <= 2 is false, and the loop stops.

int j = 1;

Declares an integer variable j and initializes it to 1. This variable represents the range of numbers (1 to 5) that 2 is multiplied by.

while (j <= 5)

The inner while loop checks if j is less than or equal to 5, allowing the program to iterate over the values 1 through 5.
        1. When j is 1, the condition j <= 5 is true, so it calculates the multiplication (i * j) and prints the result (2 * 1 = 2).
           Then j is incremented by 1 (j++), making j equal to 2.
        2. This process repeats until j is 6, at which point j <= 5 is false, and the inner loop ends.

int result = i * j;

Calculates the result of i * j and assigns it to the variable result.

System.out.print(result + “\t”);

Prints the result with a tab space (\t), formatting the output in a single line for each iteration of the inner loop.

j++;

Increments j by 1 to proceed to the next number.

System.out.println();

Prints a newline after completing one row of multiplication results, ensuring the next line is printed on a new line.

i++;

Increments i by 1 to exit the outer loop after printing the multiplication table for 2.

Output
2 4 6 8 10

Do-While Loop in Java

A do-while loop in Java is similar to a while loop, but with one key difference: it always executes its block of code at least once before checking the loop condition. After the first execution, it continues to execute as long as the specified condition remains true.

Structure of do while loop

do
// This keyword indicate the beginning of the do-while loop.
{
// Code to be executed
} while (condition); // checking condition

Do-While Loop Statement

public class Program {
    public static void main(String[] args) {
        int count = 1;
        do {
            System.out.println(“Count: ” + count);
            count++;
        } while (count <= 5);
        System.out.println(“Loop has ended.”);
    }
}

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop has ended.

Code Explanation

public class Program {

This defines a public class named Program. A class is a blueprint for creating objects, and public means that this class can be accessed from outside its containing package.

public static void main(String[] args) {

This is the entry point of your Java program. The main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program.

int count = 1;

This line declares an integer variable named count and initializes it with the value 1.

do {

This is a do-while loop. It first executes the code block inside the curly braces {} and then checks the loop condition. If the condition evaluates to true, the loop continues; otherwise, it exits.

System.out.println(“Count: ” + count);

Prints the current value of count to the console, along with the text “Count: “.

count++;

Increments the value of count by 1.

 } while (count <= 5);

This is the while loop that controls the execution of the do-while loop. It continues until the count variable exceeds the value 5.

Loop Execution:
1. The count variable value is 1, and the code inside the do block executes first, printing “Count: 1” and then incrementing count to 2. The while loop checks if count is less than or equal to 5. Since the condition is true (count = 2 and 5), the loop continues.
2. The count variable value is 2, and the code inside the do block executes again, printing “Count: 2” and then incrementing count to 3. The while loop checks if count is less than or equal to 5. Since the condition is true (count = 3 and 5), the loop continues.
3. The count variable value is 3, and the code inside the do block executes again, printing “Count: 3” and then incrementing count to 4. The while loop checks if count is less than or equal to 5. Since the condition is true (count = 4 and 5), the loop continues.
4. The count variable value is 4, and the code inside the do block executes again, printing “Count: 4” and then incrementing count to 5. The while loop checks if count is less than or equal to 5. Since the condition is true (count = 5 and 5), the loop continues.
5. The count variable value is 5, and the code inside the do block executes again, printing “Count: 5” and then incrementing count to 6. The while loop checks if count is less than or equal to 5. Since the condition is false (count = 6 and 5), the loop ends.
System.out.println(“Loop has ended.”);
● Once the loop exits (when count becomes greater than 5), this line prints “Loop has ended.” to the console.

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop has ended.

Tasks:
1. Print Odd Numbers: Use a while loop to print all odd numbers between 1 and 20. Inside the loop, use an if-else statement to check if the number is odd before printing.
2. Guess the Number: Use a do-while loop to implement a number guessing game. Use an if-else statement to check if the guessed number is higher, lower, or equal to the target number. Keep looping until the correct number is guessed.
3. Sum of Even Numbers: Use a while loop to sum all even numbers between 1 and 50. Inside the loop, use an if-else statement to check if the number is even before adding it to the sum.
4. Traffic Light Simulation: Use a do-while loop to iterate through an array of traffic light colors (“Red”, “Yellow”, “Green”). Inside the loop, use a switch statement to print the action for each color. Use an if-else statement inside the switch case for “Yellow” to print different messages for day and night.
5. Temperature Conversion: Use a while loop to iterate through an array of temperatures in Celsius. Inside the loop, convert each temperature to Fahrenheit. Use a switch statement to categorize the temperature (Cold, Warm, Hot) based on the Fahrenheit value. Use an if-else statement inside each switch case to print an appropriate message.
6. Factorial Calculation: Use a do-while loop to calculate the factorial of a number entered by the user. Use an if-else statement to check if the number is positive before calculating the factorial. Keep looping until a valid number is entered.
7. Student Grade Classification: Use a while loop to iterate through an array of student grades. Inside the loop, use a switch statement to classify the grades (‘A’, ‘B’, ‘C’, ‘D’, ‘F’). Inside each switch case, use an if-else statement to print a motivational message for grades A and B.
8. Print Prime Numbers: Use a while loop to print all prime numbers between 1 and 100. Inside the loop, use an if-else statement to check if the number is prime before printing.
9. Weekday/Weekend Checker: Use a do-while loop to iterate through an array of days of the week (“Monday”, “Tuesday”, etc.). Inside the loop, use a switch statement to print “Weekday” for Monday to Friday and “Weekend” for Saturday and Sunday. Repeat the loop until all days are processed.
10. Menu Options: Use a while loop to display a menu of options to the user. Use a switch statement to handle different menu selections. Inside each switch case, use an if-else statement to perform specific actions based on user input. Repeat the menu display until the user chooses to exit.

Course Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

A loop that repeatedly executes a block of code while a condition is true.

A loop that executes a block of code at least once before checking the condition.

while (condition) { // code block }

do { // code block } while (condition);

A while loop checks the condition first, whereas a do-while loop runs at least once before checking.

Yes, it skips the code block if the condition is initially false.

Yes, it executes the code block once regardless of the condition.

Yes, exercises like summing numbers and simulating traffic lights are included.

Yes, the tutorial is completely free.

It is designed for beginners learning Java loops.