Page Content

Tutorials

What is the While loop in Java? & What is Do-while loop?

While loop in Java

The most basic looping statement in Java is thought to be the while loop. As an entry-condition loop, it evaluates a Boolean expression before to carrying out the body of the loop. The statements inside the while block are carried out if the condition evaluates to true. Until the expression evaluates to false, this process of testing the expression and running the block keeps on.

Syntax: while (expression) { statement(s) }

Key Characteristics

  • Condition Check First: The while loop checks the conditional expression at the top of the loop.
  • Zero or More Executions: If the expression is false from the beginning, the loop’s body will not execute even once.
  • Flexibility: It is best used when the number of iterations is unknown.

Code Example (Counting 1 to 10):

class WhileDemo {
    public static void main(String[] args){
        int count = 1;
        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Another example prints the alphabet:

class WhileDemo {
    public static void main(String args[]) {
        char ch;
        // print the alphabet using a while loop
        ch = 'a';
        while(ch <= 'z') {
            System.out.print(ch);
            ch++;
        }
    }
}

Output:

abcdefghijklmnopqrstuvwxyz

Here, ch is initialised to ‘a’, and in each iteration, it is printed and then incremented until it is greater than ‘z’.

Do-while loop

The do-while loop differs from the while loop in that it is an exit-condition loop. This indicates that once the loop’s body has run, its conditional expression is evaluated at the loop’s bottom. For this reason, whether the condition is true or false at first, the statements in the do block are always run at least once.

Syntax: do { statement(s) } while (expression);

It’s important to note that the do-while statement requires a semicolon (;) after the while (expression) part.

Key Characteristics

  1. Executes At Least Once: The assurance that at least one execution will occur is the main distinction between this loop and the while loop.
  2. Condition Check Last: Every iteration concludes with an evaluation of the expression.
  3. Menu Processing: This kind of loop is very helpful when processing menu selections, as it is usually preferred to display the menu at least once.

Code Example (Counting 1 to 10):

class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Infinite Loops

A loop that never ends is said to be infinite. This happens when the conditional phrase for the loop is always true, which keeps the loop from ever getting to a false state that would let it stop. The majority of “infinite loops” are the consequence of programming mistakes, however some programming tasks like operating system command processors purposefully call for an unlimited loop to operate.

Creating Infinite Loops:

  • Using while: A simple way to create an infinite loop with while is to set its condition directly to true: while (true){ // your code goes here }
  • Using for: An infinite for loop can be created by leaving all three parts (initialisation, termination, increment) empty: for ( ; ; ) { // your code goes here }

Terminating Infinite Loops: Forcefully ending an infinite loop is possible even when it is intended to run indefinitely.

  1. break statement: The break statement can be used inside the loop to force an immediate exit, bypassing any remaining code in the loop body and the conditional test. When a break is encountered, program control resumes at the statement immediately following the loop.
  2. External Intervention: To end the execution of a program that is being run from a command prompt, use Ctrl + C. Additionally, halt functions are offered by development environments such as NetBeans.

Differences between while and do-while loops

The basic difference between while and do-while loops is the timing of the condition evaluation.

  • Because the while loop is an entry-condition loop, its body may not run at all because it only checks the condition at the start.
  • An exit-condition loop, the do-while loop ensures that its body will run at least once by checking the condition at the end.

The decision between while and do-while essentially comes down to whether the task needs to be completed at least once before the condition is verified.

Loops in Java programming are control flow statements that allow a program to run a block of instructions repeatedly until a predetermined termination condition is satisfied. This feature is essential for activities that call for repeated actions, including doing calculations, processing user input repeatedly, or iterating over collections. While, do-while, and for loops are the three main looping techniques offered by Java; an improved for-each loop is also available for arrays and collections.

Index