🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

do-while Loop

Java Do-While Loop Examples

In Java, the do-while loop is a variation of the while loop. The key difference is that the do-while loop guarantees that the block of code is executed at least once, even if the loop condition is initially false. The basic syntax of the do-while loop is as follows:

do {
    // Code to be executed
} while (condition);

Example:

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

        do {
            System.out.println(i);
            i++;
        } while (i <= 5);
    }
}

In this example:

  • int i = 1; initializes a loop control variable i to 1.
  • The do block contains the code to be executed. In this case, it prints the value of i.
  • i++; increments the value of i after each iteration.
  • The while (i <= 5); is the loop condition. The loop will continue as long as the condition is true.

The output of this program will be:

1
2
3
4
5

Even if the condition is initially false, the code inside the do block is executed at least once before checking the condition. This makes the do-while loop suitable when you want to ensure that a certain block of code runs at least once, regardless of the initial condition.

Example with Initially False Condition:

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

        do {
            System.out.println("This will be printed at least once.");
        } while (i < 3);
    }
}

In this case, the message inside the do block will be printed once, even though the condition is initially false.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.