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

while Loop

Java While Loop Examples

In Java, the while loop is used to repeatedly execute a block of code as long as a given boolean expression evaluates to true. The loop continues iterating as long as the condition remains true. The basic syntax of the while loop is as follows:

while (condition) {
    // Code to be executed as long as the condition is true
}

Example:

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

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

In this example:

  • int i = 1; initializes a loop control variable i to 1.
  • while (i <= 5) is the loop condition. As long as this condition is true, the loop continues.
  • System.out.println(i); prints the value of i.
  • i++; increments the value of i after each iteration.

The output of this program will be:

1
2
3
4
5

Infinite while Loop:

Be cautious when using a while loop to avoid an infinite loop (a loop that never terminates). If the loop condition always evaluates to true, the loop will continue indefinitely. For example:

// Caution: Infinite loop
while (true) {
    // Code inside the loop
}

In the above example, the loop will never exit because the condition is always true. It's important to ensure that the loop condition will eventually become false to prevent infinite loops.

Do-While Loop:

The do-while loop is similar to the while loop, but it guarantees that the block of code is executed at least once, even if the loop condition is initially false. The syntax 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, the loop will execute at least once, printing numbers from 1 to 5.

The choice between while and do-while depends on whether you want the block of code to be executed at least once, regardless of the initial condition.

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.